← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 4 of 8

Java finally Block

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?

java
public class Main {
	public static void main(String[] args) {
		try {
			System.out.println("try");
		} finally {
			System.out.println("finally always runs");
		}
	}
}

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

java
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
		}
	}
}

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

java
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");
		}
	}
}

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

java
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());
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.