ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.