Java finally Block
In this page:
try {
// code
} catch (ExceptionType e) {
// handle
} finally {
// always runs
}
What is the finally Block?
The finally block runs after try/catch regardless of whether an exception was thrown, caught, or not thrown at all. It exists specifically for cleanup code that absolutely must execute no matter what happened.
Example: What is the finally Block?
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Try code that might throw an exception
try {
// Print a line to the console
System.out.println("try");
// Always runs, whether or not an exception occurred
} finally {
// Print a line to the console
System.out.println("finally always runs");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Cleaning Up Resources
Closing files, database connections, or network sockets is the classic use for finally — you open the resource before the try, and release it in finally so a leak can't happen even if an exception interrupts the middle of the operation.
Example: Cleaning Up Resources
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("data.txt");
try {
writer.write("Hello");
} finally {
writer.close(); // resource released no matter what
}
}
}
Login to try C/C++/Java/PHP code in the editor
finally with Uncaught Exceptions
If an exception isn't caught by any matching catch block, finally still runs before the exception propagates up to the caller. This guarantees cleanup happens even for errors your code didn't anticipate.
Example: finally with Uncaught Exceptions
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
// Try code that might throw an exception
try {
method();
// Handle RuntimeException if it was thrown
} catch (RuntimeException e) {
// Print a line to the console
System.out.println("Caught in main");
}
}
static void method() {
// Try code that might throw an exception
try {
// Throw RuntimeException to signal an error
throw new RuntimeException("boom");
// Always runs, whether or not an exception occurred
} finally {
System.out.println("finally runs before propagating");
}
}
}
Login to try C/C++/Java/PHP code in the editor
finally vs Return Statements
A return inside finally silently overrides a return from try or catch, discarding whatever value they were about to return — a subtle bug source, so avoid returning from finally unless you mean to replace the result.
Example: finally vs Return Statements
public class Main {
static int test() {
try {
return 1;
} finally {
return 2; // silently overrides the try's return
}
}
public static void main(String[] args) {
System.out.println(test());
}
}
Login to try C/C++/Java/PHP code in the editor
When finally Does Not Execute
finally is skipped only in extreme cases: if the JVM itself terminates (via System.exit() or a crash) or if the thread running it is forcibly killed mid-execution. For virtually all normal control flow, it's guaranteed to run.
Example: When finally Does Not Execute
public class Main {
public static void main(String[] args) {
try {
System.out.println("try");
System.exit(0); // finally is skipped after this
} finally {
System.out.println("This never prints");
}
}
}
Login to try C/C++/Java/PHP code in the editor
- Using
returninsidefinally, which discards the original exception or return value. - Expecting
finallyto run afterSystem.exit(), when it does not. - Putting code that can throw in
finallywithout handling it.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: