finally Keyword in Java
The finally keyword in Java is a block used in exception handling that guarantees the execution of code regardless of whether an exception was thrown or caught. It's most commonly used to release resources such as closing files, database connections, or network sockets.
Why Use the finally Block?
Imagine you're opening a file or a database connection. Whether your program succeeds or fails, you must ensure the resource is released properly. That’s where finally comes in — it runs no matter what.
Syntax of try-catch-finally
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling
} finally {
// Code that will always execute
}
Example 1: Basic try-catch-finally Structure
public class FinallyExample {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
int result = 10 / 2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Catch block: " + e.getMessage());
} finally {
System.out.println("Finally block always runs");
}
}
}
Inside try block
Result: 5
Finally block always runs
Explanation
Since no exception is thrown, the catch block is skipped. But the finally block runs anyway.
Example 2: When Exception Is Thrown
public class FinallyExample {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
int result = 10 / 0; // Throws ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Catch block: " + e.getMessage());
} finally {
System.out.println("Finally block always runs");
}
}
}
Inside try block
Catch block: / by zero
Finally block always runs
Even When No Catch Block Exists
The finally block can be used with try even if catch is absent. This is useful when you don't want to handle exceptions but still need cleanup.
public class FinallyOnlyExample {
public static void main(String[] args) {
try {
System.out.println("Trying risky operation...");
int result = 10 / 0;
} finally {
System.out.println("Cleanup happens here.");
}
}
}
Trying risky operation...
Cleanup happens here.
Exception in thread "main" java.lang.ArithmeticException: / by zero
Even When return Is Called
What if we return from inside a try? Will finally still run? Absolutely yes.
public class ReturnWithFinally {
public static void main(String[] args) {
System.out.println(testReturn());
}
static String testReturn() {
try {
return "Returning from try";
} finally {
System.out.println("Finally still executes before return");
}
}
}
Finally still executes before return
Returning from try
Key Points to Remember
finallyalways runs, whether or not an exception is thrown or caught.- It runs even if there is a
returnstatement in thetryorcatchblock. - Use it for cleanup operations like closing file streams or network connections.
- Even when an exception is unhandled and the program crashes, the
finallyblock still executes.
Use Case: Closing a File
import java.io.*;
public class FileHandling {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("file.txt"));
System.out.println("First line: " + reader.readLine());
} catch (IOException e) {
System.out.println("Something went wrong: " + e.getMessage());
} finally {
try {
if (reader != null) reader.close();
System.out.println("Reader closed in finally block");
} catch (IOException ex) {
System.out.println("Failed to close reader");
}
}
}
}
Comments
Loading comments...