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

Java finally Block

The finally block is code that always runs, whether things worked or not, like turning off the lights when you leave a room either way. It is used for clean-up.
Syntax
java
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?

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

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

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");
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using return inside finally, which discards the original exception or return value.
  2. Expecting finally to run after System.exit(), when it does not.
  3. Putting code that can throw in finally without handling it.

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.