Java finally Block
In this page:
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?
public class Main {
public static void main(String[] args) {
try {
System.out.println("try");
} finally {
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
public class Main {
public static void main(String[] args) {
try {
method();
} catch (RuntimeException e) {
System.out.println("Caught in main");
}
}
static void method() {
try {
throw new RuntimeException("boom");
} 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
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: