In this lesson, you will learn
finally block contains code that is always executed after the try and catch blocks, regardless of whether an exception was thrown or caught.
try {
// Code that might throw an exception
} catch (ExceptionType name) {
// Handling code
} finally {
// Cleanup code, always executed
}
package l4;
public class FinallyBlockExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: "
+ e.getMessage());
} finally {
System.out.println("This will always be printed.");
}
}
}
Caught ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
This will always be printed.
Note: The finally clause is optional. However, each try statement requires at least one catch or a finally clause otherwise the compilation error will occur.
public class CompileTimeExample {
public static void main(String[] args) {
int x;
try {
x=10/0;
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "Finally" to complete TryStatement
at stringdemo.CompileTimeExample.main(CompileTimeExample.java:9)
try block followed by a finally block without a catch block is a valid construct
Here’s what happens in different scenarios:
try block, the finally block executes and then the control moves to the next part of the code.try block and is not caught (because there is no catch block), the finally block still executes. After the finally block completes, the exception is propagated up the call stack to be handled elsewhere.
try {
// Code that might throw an exception
}
finally {
// Cleanup code, always executed
}
package l4;
public class FinallyBlockExample2 {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]);
}
finally {
System.out.println("This will always be printed.");
}
System.out.println("Exiting application.....");
}
}
This will always be printed.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 3 out of bounds for length 3
at l4.FinallyBlockExample2.main(FinallyBlockExample2.java:7)
Almost all variations are discussed.
You must be logged in to submit a review.