Finally Block
1. Introduction
In Java exception handling, the finally block is used to execute code that must run regardless of whether an exception occurs or not.
The finally block is typically used for cleanup operations, such as:
- closing files
- closing database connections
- releasing resources
- closing network sockets
Because the finally block always executes (with very few exceptions), it ensures that important resources are properly released.
2. Basic Syntax
The finally block is written after a try block and optional catch block.
try {
// risky code
} catch (Exception e) {
// exception handling
} finally {
// cleanup code
}Key points:
finallyis optional.- It always executes after
tryandcatch. - It executes even if an exception occurs.
3. Execution Flow
There are three possible scenarios when using try, catch, and finally.
Case 1: No Exception Occurs
try {
System.out.println("Inside try");
} catch (Exception e) {
System.out.println("Inside catch");
} finally {
System.out.println("Inside finally");
}Output:
Inside try
Inside finallyExplanation:
- No exception occurs
catchblock is skippedfinallystill runs
Case 2: Exception Occurs and Is Handled
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled");
} finally {
System.out.println("Finally block executed");
}Output:
Exception handled
Finally block executedExplanation:
- Exception occurs
catchblock handles itfinallyexecutes afterward
Case 3: Exception Occurs but Not Handled
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} finally {
System.out.println("Finally block executed");
}Output:
Finally block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsExceptionExplanation:
- Exception occurs
- No
catchblock exists finallystill executes- Program terminates afterward
4. Using Try-Finally Without Catch
Java allows try with finally even without catch.
Example:
try {
System.out.println("Inside try block");
} finally {
System.out.println("Cleanup code executed");
}Output:
Inside try block
Cleanup code executedThis structure is commonly used when we want to ensure cleanup but do not need to handle the exception here.
5. Real Example: Closing Resources
Before Java introduced try-with-resources, the finally block was commonly used to close resources.
Example:
import java.io.FileReader;
public class Demo {
public static void main(String[] args) throws Exception {
FileReader reader = null;
try {
reader = new FileReader("data.txt");
System.out.println("File opened");
} finally {
if (reader != null) {
reader.close();
System.out.println("File closed");
}
}
}
}The finally block guarantees that the file is closed.
6. Finally with Return Statements
Even if a return statement is used inside try or catch, the finally block still executes.
Example:
public class Demo {
static int test() {
try {
return 10;
} finally {
System.out.println("Finally executed");
}
}
public static void main(String[] args) {
System.out.println(test());
}
}Output:
Finally executed
10Explanation:
tryreturns value- before returning,
finallyexecutes
7. Finally with Exception
Even when an exception occurs, finally executes.
Example:
public class Demo {
public static void main(String[] args) {
try {
int x = 10 / 0;
} finally {
System.out.println("Finally always runs");
}
}
}Output:
Finally always runs
Exception in thread "main" java.lang.ArithmeticException8. When Finally May Not Execute
There are rare situations where the finally block may not run:
- JVM crashes
- System shutdown
System.exit()is called
Example:
try {
System.exit(0);
} finally {
System.out.println("This will not run");
}Here the JVM stops immediately.
9. Modern Alternative: Try-With-Resources
Java 7 introduced try-with-resources, which automatically closes resources.
Example:
import java.io.FileReader;
public class Demo {
public static void main(String[] args) throws Exception {
try (FileReader reader = new FileReader("data.txt")) {
System.out.println("File opened");
}
}
}The resource is automatically closed.
This reduces the need for finally blocks for resource cleanup.
10. Best Practices
- Use
finallyfor cleanup tasks. - Avoid complex logic inside
finally. - Prefer
try-with-resourcesfor managing resources. - Do not modify return values inside
finally. - Keep
finallyblock simple and focused.
11. Summary
- The
finallyblock executes aftertryandcatch. - It runs whether an exception occurs or not.
- It is mainly used for resource cleanup.
- Even if
returnis used intry,finallystill executes. - Modern Java prefers
try-with-resourcesfor automatic resource handling.
Written By: Shiva Srivastava
How is this guide?
Last updated on
