❔ What is a finally block?
The finally block is used to write code that must be executed, no matter what happens in the try-catch block.
It runs whether an exception is thrown or not, caught or not, or even if there’s a return statement.
🔧 Syntax:
try {
// code that might throw exception
} catch (Exception e) {
// handling code
} finally {
// cleanup code that always runs
}💡 Real-Life Analogy
Imagine leaving a room:
Whether you leave normally or there's a fire alarm,
➡️ you still lock the door before leaving.
That "always executed step" is like the finally block.
✅ Example: Normal Execution
public class Main {
public static void main(String[] args) {
try {
System.out.println("Try block executed");
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block always runs");
}
}
}Try block executed
Finally block always runs⚠️ Example: With Exception
public class Main {
public static void main(String[] args) {
try {
int a = 10 / 0; // causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e);
} finally {
System.out.println("Finally block runs anyway");
}
}
}Caught exception: java.lang.ArithmeticException: / by zero
Finally block runs anyway⚡ Special Case: Return in Try
Even if there's a return statement inside try, finally still runs.
public class Main {
public static int test() {
try {
return 1;
} finally {
System.out.println("Finally still runs");
}
}
public static void main(String[] args) {
System.out.println("Returned: " + test());
}
}Finally still runs
Returned: 1🧠 When to Use finally?
To close resources (files, database connections, streams)
To log important info
To ensure cleanup, no matter what
🧾 Recap Table
Block | Runs When? |
|---|---|
| Always first; runs code that might break |
| If exception occurs, this handles it |
| ✅ Always runs, even with return or error |