Category: java
finally
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:
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:
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:
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:
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:
try {
System.exit(0);
} finally {
System.out.println("This will not execute");
}