Java program to implement finally block when an exception is caught

Java example to implement finally block when an exception is caught.
Submitted by Nidhi, on April 19, 2022

Problem Solution:

In this program, we will use finally block with a try, catch. Here we will catch generated exception.

The finally block is a block that executes whether an exception rise or not and whether the exception is handled or not.

Program/Source Code:

The source code to implement the finally block when the exception is caught is given below. The given program is compiled and executed successfully.

// Java program to implement finally block 
// when an exception is 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 (ArithmeticException e) {
      System.out.println("Exception: " + e);
    } finally {
      System.out.println("The finally block executed");
    }

    System.out.println("Program Finished");
  }
}

Output:

Exception: java.lang.ArithmeticException: / by zero
The finally block executed
Program Finished

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 caught by the catch block, and the finally block executes.

Java Exception Handling Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.