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 Propagation.
Exception Propagation in Unchecked Exceptions
when an exception happens, Propagation is a process in which the exception is being dropped from to the top to the bottom of the stack. If not caught once, the exception again drops down to the previous method and so on until it gets caught or until it reach the very bottom of the call stack. This is called exception propagation and this happens in case of Unchecked Exceptions.
In the example below, exception occurs in m() method where it is not handled, so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method, p() method, n() method or m() method.
Note : By default, Unchecked Exceptions are forwarded in calling chain (propagated).
Exception handled Normal flow...
Exception Propagation in Checked Exceptions
Unlike Unchecked Exceptions, the propagation of exception does not happen in case of Checked Exception and its mandatory to use throw keyword here. Only unchecked exceptions are propagated. Checked exceptions throw compilation error.
In example below, If we omit the throws keyword from the m() and n() functions, the compiler will generate compile time error. Because unlike in the case of unchecked exceptions, the checked exceptions cannot propagate without using throws keyword.
Note : By default, Checked Exceptions are not forwarded in calling chain (propagated).
exception handled normal flow...
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.