Practical-42
Write a java program which uses finally Statement.
Answer 1:
Introduction
Java’s finally statement is designed to always execute regardless of the result of the try/catch statement, and acts as a catch-all for operations that must complete even in the face of an exception. A finally statement ensures code is executed at the end of a try/catch block, no matter if an exception is thrown or not. This code is useful for clean-up operations, such as closing files and connections.
Code
try {
int [] numbers = {1,2,3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("There was an exception thrown: " + e.toString());
} finally {
System.out.println("The finally statement has been executed.");
}
Output
There was an exception thrown: java.lang.ArrayIndexOutOfBoundsException: 5
The finally statement has been executed.
Explanation
The try/catch statement captures the exception when an incorrect index of an array is used. The finally statement then executes after the catch block, displaying the message: “The finally statement has been executed.”