Home »
Java »
Java Programs
Java program to implement finally block when the exception is not caught
Java example to implement finally block when the exception is not caught.
Submitted by Nidhi, on April 19, 2022
Problem statement
In this program, we will use finally block with a try, catch. Here we will not catch generated exceptions.
The finally block is a block that executes whether an exception rise or not and whether the exception is handled or not.
Source Code
The source code to implement the finally block when an exception is not caught is given below. The given program is compiled and executed successfully.
// Java program to implement finally block
// when the exception is not caught
public class Main {
public static void main(String[] args) {
try {
int a = 10, b = 0, c = 0;
c = a / b;
System.out.println("Division is: " + c);
} catch (NullPointerException e) {
System.out.println("Exception: " + e);
} finally {
System.out.println("The finally block executed");
}
System.out.println("Program Finished");
}
}
Output
The finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:9)
Explanation
In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.
Here, we created try, catch, and finally blocks. In the try block, it generates a divide by zero exception which is not caught by the catch block. But the finally block executes whether an exception rise or not and whether the exception is handled or not.
Java Exception Handling Programs »