Exceptions thrown during execution of the try block can be caught and handled in a catch block. A finally block is guaranteed to be executed, regardless of the cause of exit from the try block, or whether any catch block was executed.
Few points to note:
- For each try block there can be zero or more catch blocks, but only one finally block.
- The catch blocks and the finally block must always appear in conjunction with a try block, and in the right order.
- A try block must be followed by at least one catch block or a finally block must be specified.
Let us try to understand the try-catch-finally flow.
The try block establishes a context for exception handling. Termination of a try block occurs as a result of encountering an exception, or from successful execution of the code in the try block.
The catch blocks are skipped for all normal exits from the try block where no exceptions were raised, and control is transferred to the finally block if one is specified.
For all exits from the try block resulting from exceptions, control is transferred to the catch blocks—if any such blocks are specified—to find a matching catch block.If no catch block matches the thrown exception, control is trans- ferred to the finally block if one is specified.
The finally Block
The finally block is guaranteed to be executed, regardless of whether any catch block was executed. Since the finally block is always executed, the finally block can be used to specify any clean-up code (e.g., to free resources such as files,database connections).
Let us consider the following three scenarios:
1. No Exception is thrown
package com.blog;
public class NoException {
public static void main(String[] args) {
try{
System.out.println(“Inside try”);
}catch(Exception ex){
System.out.println(“Inside catch”);
System.out.println(ex);
}finally{
System.out.println(“Inside finally”);
}
}
}
Output:
Inside try
Inside finally
2. Exception is thrown and handled
package com.blog;
public class ExceptionHandled {
public static void main(String[] args) {
try{
System.out.println(“Inside try”);
int i = 10/0;
}catch(ArithmeticException ex){
System.out.println(“Inside catch”);
System.out.println(ex);
}finally{
System.out.println(“Inside finally”);
}
}
}
Output:
Inside try
Inside catch
java.lang.ArithmeticException: / by zero
Inside finally
3. Exception is thrown and not handled
package com.blog;
public class ExceptionNotHandled {
public static void main(String[] args) {
try{
System.out.println(“Inside try”);
int i = 10/0;
}catch(NullPointerException ex){
System.out.println(“Inside catch”);
System.out.println(ex);
}finally{
System.out.println(“Inside finally”);
}
}
}
Output:
Hello Gyan,
I have a doubt regarding “try with resources” concept that came post JDK 1.7 in order to suppress the job done by finally block.
It would be very helpful if you find some time and put your thoughts on that concept.
Will check on this 🙂