Q:

Java program to implement finally block when an exception is caught

belongs to collection: Java Exception Handling Programs

0

Java program to implement finally block when an exception is caught

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 trycatch, 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to throw an exception explicitly... >>
<< Java program to implement finally block when the e...