Exception Handling
Java Program to Demonstrate Finally Block
A Java program to demonstrate the usage of the finally block.
Problem Description
Write a Java program to demonstrate the usage of the finally block in exception handling.
Code
public class FinallyBlock {
public static void main(String[] args) {
try {
int data = 25 / 5;
System.out.println(data);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}Output
5
finally block is always executed
rest of the code...Explanation
finallyBlock: Executed regardless of whether an exception is handled or not.- Usage: Used to close resources like files or database connections.
