Java the Finally Statement with Examples

Java the Finally Statement with Examples


Finally Statement With Examples In Java
There’s often some piece of code that you want to execute whether or not an exception is thrown within a try block.
This usually pertains to some operation other than memory recovery (since that’s taken care of by the garbage collector). 
To achieve this effect, you use a finally clause4 at the end of all the exception handlers.
try {
// The guarded region: Dangerous activities
// that might throw A, B, or C
} catch(A a1) {
// Handler for situation A
} catch(B b1) {
// Handler for situation B
} catch(C c1) {
// Handler for situation C
} finally {
// Activities that happen every time
}
The finally clause is necessary when you need to set something other than memory back to its original state. This is some kind of cleanups like an open file or network connection, something you’ve drawn on the screen, or even a switch in the outside world, as modeled in the following example - 
Example -
 
class FourException extends Exception {}
public class AlwaysFinally {
public static void main(String[] args) {
print("Entering first try block");
try {
print("Entering second try block");
try {
throw new FourException();
} finally {
print("finally in 2nd try block");
}
} catch(FourException e) {
System.out.println(
"Caught FourException in 1st try block");
} finally {
System.out.println("finally in 1st try block");
}
}
}
 
Output -  
 
Entering first try block
Entering second try block
finally in 2nd try block
Caught FourException in 1st try block
finally in 1st try block