In this article, we will discuss exception propagation in detail with example
1. Exception propagation:
- Whenever exception is raised from method and if it isn’t handled in the same method, then it is propagated back to the caller-method
- This step is repeated until handler code is found in one of the caller-method in the runtime stack or else it reaches bottom of the runtime-stack
- This is known as Exception propagation
2. Rules for Exception propagation:
- By default, unchecked-exception is propagated back to the runtime-stack one-by-one until it finds handler code or it reaches bottom of the stack
- Checked-exception isn’t propagated, rather compiler forces the programmer to handle checked-exception in the same method by surrounding with try-catch block or declaring with throws keyword
3. Example for Exception propagation
- Exception propagation w.r.t Unchecked Exception
- Exception propagation w.r.t Checked Exception
- Explicit propagation w.r.t Unchecked Exception
3.1 Exception propagation w.r.t Unchecked exception:
In this example,
- When arithmetic-exception is raised in methodThree(), then it isn’t handled. Therefore, it is propagated back to the caller-method i.e.; methodTwo()
- Similarly, there is no handler-code available in methodTwo() also
- Therefore, again it is propagated back to the caller method i.e.; methodOne()
- Like this, it will be repeated until if finds a suitable handler-code or till it reached bottom of the runtime-stack
- In this case, there is no handler code till it reaches the bottom of the stack
- Finally JVM passes the control to Default-exception-handler along with exception object when no handler-code is found (i.e.; propagation reaches the main() method i.e.; last entry in the runtime-stack)
- Default-exception-handler prints exception-information it has got from exception-object and terminates method abnormally
DefaultPropagationForUncheckedException.java
package in.bench.resources.exception.handling;
public class DefaultPropagationForUncheckedException {
// main() method - start of JVM execution
public static void main(String[] args) {
callMethodOne();
}
// callMethodOne() method
public static void callMethodOne() {
callMethodTwo();
}
// callMethodTwo() method
public static void callMethodTwo() {
callMethodThree();
}
// callMethodThree() method
public static void callMethodThree() {
// performing arithmetic operation
int result = 19/0;
System.out.println("The result of division is : "
+ result);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException:/ by zero
at in.bench.resources.exception.handling
.DefaultPropagationForUncheckedException
.callMethodThree(DefaultPropagationForUncheckedException.java:24)
at in.bench.resources.exception.handling
.DefaultPropagationForUncheckedException
.callMethodTwo(DefaultPropagationForUncheckedException.java:17)
at in.bench.resources.exception.handling
.DefaultPropagationForUncheckedException
.callMethodOne(DefaultPropagationForUncheckedException.java:12)
at in.bench.resources.exception.handling
.DefaultPropagationForUncheckedException
.main(DefaultPropagationForUncheckedException.java:7)
3.2 Exception propagation w.r.t Checked exception:
Whenever checked exception is thrown, then compiler throws compile-time error stating “Unhandled exception type exception-class-name”
- So default propagation like in earlier case for unchecked exception isn’t possible for this case (with checked exception)
- Because, compiler forces/tells with an compile-time error to handle the checked exception either with a try-catch block combination or declaring throws clause
- Therefore, it is must for checked exception to handle
- Not providing handler-code leads to compile-time error
- Note: default propagation isn’t possible for checked exception but programmer can manually propagate using throw keyword
- Move over to next example for explanation
NoPropagationForCheckedException.java
3.3 Explicit propagation for Checked exception:
- Explicitly, we can propagate checked exception too by declaring with throws clause
- But it must be handled in one of the method in the runtime stack
- Otherwise compile-time error will be thrown stating “Unhandled exception type exception-class-name”
- In the below example for explicitly throwing checked exception, last entry in the runtime stack i.e.; main() method handled exception by surrounding the call with try-catch block
ExplicitPropagationForCheckedException.java
package in.bench.resources.exception.handling;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class ExplicitPropagationForCheckedException {
// main() method - start of JVM execution
public static void main(String[] args) {
try {
callMethodOne();
}
catch (FileNotFoundException fnfex) {
System.out.println("Exception handled successfully");
}
System.out.println("By handling for checked exception,"
+ " program terminates gracefully");
}
// callMethodOne() method
public static void callMethodOne()
throws FileNotFoundException {
callMethodTwo();
}
// callMethodTwo() method
public static void callMethodTwo()
throws FileNotFoundException {
callMethodThree();
}
// callMethodThree() method
public static void callMethodThree()
throws FileNotFoundException {
// performing IO operation assumed that,
// we are trying to access file from remote location
FileReader fileReader = new FileReader(
"D:/Folder/test.txt");
}
}
Output:
Exception handled successfully
By handling for checked exception, program terminates gracefully
Conclusion:
- By default, unchecked exception are propagated back to the runtime stack until it reaches bottom of the stack or else it finds handler code
- By default, checked exception aren’t propagated; because whenever there is possibility of raising checked exception then compiler forces/tells to handle it
- But explicit propagation for checked exception is possible by use of throws keyword
Related Articles:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!