Java Program to Use finally block for Catching Exceptions
Last Updated :
27 Nov, 2020
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.
There are 3 possible cases where finally block can be used:
Case 1: When an exception does not rise
In this case, the program runs fine without throwing any exception and finally block execute after the try block.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println( "inside try block" );
System.out.println( 34 / 2 );
}
catch (ArithmeticException e) {
System.out.println( "Arithmetic Exception" );
}
finally {
System.out.println(
"finally : i execute always." );
}
}
}
|
Output
inside try block
17
finally : i execute always.
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block, and finally block executes after the catch block.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println( "inside try block" );
System.out.println( 34 / 0 );
}
catch (ArithmeticException e) {
System.out.println(
"catch : exception handled." );
}
finally {
System.out.println( "finally : i execute always." );
}
}
}
|
Output
inside try block
catch : exception handled.
finally : i execute always.
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so finally block execute after the try block and after the execution of finally block program terminate abnormally, But finally block execute fine.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println( "Inside try block" );
System.out.println( 34 / 0 );
}
catch (NullPointerException e) {
System.out.println(
"catch : exception not handled." );
}
finally {
System.out.println(
"finally : i will execute always." );
}
System.out.println( "i want to run" );
}
}
|
Output
Inside try block
finally : i will execute always.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...