In: Computer Science
Java Question:
What is exception propagation? Give an example of a class that contains at least two methods, in which one method calls another. Ensure that the subordinate method will call a predefined Java method that can throw a checked exception. The subordinate method should not catch the exception. Explain how exception propagation will occur in your example.
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
Exception propagation : An exception is first
thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method.
After a method throws an exception, the runtime system attempts to
find something to handle it. The set of possible “somethings” to
handle the exception is the ordered list of methods that had been
called to get to the method where the error occurred. The list of
methods is known as the call stack and the method
of searching is Exception
import java.io.IOException;
class Simple {
// exception propagated to n()
void m() throws IOException
{
// checked exception occurred
throw new IOException("device error");
}
// exception propagated to p()
void n() throws IOException
{
m();
}
void p()
{
try {
// exception handled
n();
}
catch (Exception e) {
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Simple obj = new Simple();
obj.p();
System.out.println("normal flow...");
}
}
Kindly revert for any queries
Thanks.