Category: React • Beginner
Published on 18 Feb 2026
Explanation
finally is a block in Java used with try and catch. It always executes whether an exception occurs or not.
Code Example
try {
int a = 10 / 2;
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block executed");
}
Explanation
finally is mainly used to close resources like database connections, files, or streams to ensure cleanup.
Code Example
try {
// database code
} finally {
System.out.println("Closing connection");
}
Explanation
Even if an exception occurs in the try block, the finally block will still execute.
Code Example
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled");
} finally {
System.out.println("Always runs");
}
Explanation
A try block can be followed directly by finally without a catch block.
Code Example
try {
System.out.println("Inside try");
} finally {
System.out.println("Inside finally");
}
Explanation
finally block will not execute only in rare cases like System.exit() call or JVM crash.
Code Example
try {
System.exit(0);
} finally {
System.out.println("This will not execute");
}