ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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.

Program/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 »


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.