In this article, we will discuss whether finally-block always gets executed, even if there is a return statement in try-block or catch-block or both try-catch blocks for valid cases
To discuss this topic, we will consider one of the valid case from previous article i.e.; method returning from try-block & catch-block and it also contains finally-block with some statements i.e.; Case-6 in that article
1. Happy Scenario
- No exception is raised from try-block
- and value is returned from try-block
ReturnValueExample.java
package in.bench.resources.exception.handling;
public class ReturnValueExample {
public static void main(String[] args) {
// invoking static method
System.out.println(returnValueFromMethod());
}
// method enclosed with try-catch-finally blocks
// and returns-value
public static int returnValueFromMethod() {
int result = 0;
try {
result = 18/3;
return result;
}
catch(ArithmeticException aex) {
System.out.println(aex.toString());
return -1;
}
finally {
System.out.println("finally block"
+ " always executed for resource clean-up");
}
}
}
Output:
finally block always executed for resource clean-up
6
2. Exception Scenario
- Exception is raised & it is caught in the catch-block
- and value is returned from catch-block
ReturnValueExample.java
package in.bench.resources.exception.handling;
public class ReturnValueExample {
public static void main(String[] args) {
// invoking static method
System.out.println(returnValueFromMethod());
}
// method enclosed with try-catch-finally blocks
// and returns value
public static int returnValueFromMethod() {
int result = 0;
try {
result = 18/0;
return result;
}
catch(ArithmeticException aex) {
System.out.println(aex.toString());
return -1;
}
finally {
System.out.println("finally block"
+ " always executed for resource clean-up");
}
}
}
Output:
java.lang.ArithmeticException: / by zero
finally block always executed for resource clean-up
-1
Explanation:
- In both scenarios i.e.; Happy scenario as well as Exception scenario, finally-block always gets executed
Now next question is,
Q) Whether finally-block always executed irrespective of whether exception thrown or NOT and whether it is handled or NOT ?
- The answer is certainly yes
- but on one condition finally-block won’t gets executed
- when program encounters some statement which will kill the program execution further
- like System.exit(0);
ReturnValueExample.java
package in.bench.resources.exception.handling;
public class ReturnValueExample {
public static void main(String[] args) {
// invoking static method
System.out.println(returnValueFromMethod());
}
// method enclosed with try-catch-finally blocks
// and returns-value
public static int returnValueFromMethod() {
int result = 0;
try {
result = 18/3;
System.exit(0);
return result;
}
catch(ArithmeticException aex) {
System.out.println(aex.toString());
return -1;
}
finally {
System.out.println("finally block"
+ " always executed for resource clean-up");
}
}
}
Explanation:
- When above program is executed, it doesn’t print anything in the console
- because it encounters System.exit(0); just before return statement & program terminates
3. Highlight of return statement in finally-block:
It is valid sequence to have return statements in all three blocks i.e.;
- try-block
- catch-block
- finally-block
Q) What will happen, when return statement is encountered in finally block ?
- return-value from try-block for successful execution will be overridden by return-value in the finally-block
- return-value from catch-block for exception thrown will be overridden by return-value in the finally-block
4. finally-block overrides return-value from try-block and catch-block
- Let us see 2 examples for this scenario:
1. Successful execution and return statement from try-block
Explanation:
- Above program execution should return integer-value 6 from try-block
- But from above program output, it is seen that it is returning integer value 1,
- because return-value from try-block is overridden when control flows to finally-block
- As we all know, finally-block always gets executed irrespective of whether exception is raised or NOT & whether that exception is caught or NOT
- Therefore, any statement inside finally-block will be executed before encountering a return statement
- Error-scenario : if we keep any statement inside finally-block after return statement or after finally-block, then it raises compile-time error stating “Unreachable code”
2. Successful execution and return statement from catch-block
Explanation:
- Above program execution raises exception as there is a divide by zero calculation inside try-block
- Exception raised from try-block gets caught in the catch-block and catch-block returns integer value -1
- But from above program output, it is seen that it is returning integer value 1, because return-value from catch-block is overridden when control flows to finally-block
- As we all know, finally-block always gets executed irrespective of whether exception is raised or NOT & whether that exception is caught or NOT
- Therefore, any statement inside finally-block will be executed before encountering a return statement
- Error-scenario : if we keep any statement inside finally-block after return statement or after finally-block, then it raises compile-time error stating “Unreachable code”
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:
- 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 !!