🌪️ What is try-catch-finally
?
This is Java’s exception handling mechanism to catch errors that happen during runtime and gracefully recover (instead of crashing the program).
try
— Code that might throw an exception.catch
— Code that handles the exception.finally
— Code that always runs, whether an exception occurred or not (cleanup logic like closing files or connections).
📜 Basic Structure
try {
// Risky code (could throw an exception)
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Cleanup code (always runs, even if exception is thrown)
}
✅ Example — Division Handling
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This always runs (cleanup)");
}
}
static int divide(int a, int b) {
return a / b;
}
}
Cannot divide by zero: / by zero
This always runs (cleanup)
⚙️ Flow Explanation
Step | What happens? |
---|---|
Enter try block | Risky code runs |
Exception thrown? | Yes — Jump to catch |
catch block runs | Handles the exception |
finally block runs | Runs always (whether exception or not) |
🔗 Important Rules
Case | What Happens? |
---|---|
No exception | try runs fully, finally runs, catch skipped |
Exception thrown | try stops, jumps to matching catch , then finally runs |
Exception thrown but not caught | finally still runs before propagating exception up |
Exception inside finally | That new exception can replace the original one |
🎯 Key Properties of finally
- Guaranteed execution (unless JVM exits via
System.exit()
or crash). - Used for closing resources, releasing locks, etc.
- In modern Java (Java 7+), you often use try-with-resources instead (more on that later).
🔥 Example — Multiple Catch Blocks
try {
int[] nums = {1, 2};
System.out.println(nums[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Math error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error"); // This block will catch
} finally {
System.out.println("Always cleanup");
}
Output
Array index error
Always cleanup
🔄 Modern Alternative — Try-with-Resources (Java 7+)
For resources like files or sockets, instead of:
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// read file
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
try (FileInputStream fis = new FileInputStream("file.txt")) {
// read file
} catch (IOException e) {
e.printStackTrace();
}
- No
finally
needed — resource closes automatically.
⚠️ What happens if finally
has a return
?
This is a tricky case and a popular interview question.
public int riskyMethod() {
try {
return 1;
} finally {
return 2; // This overrides the try return!
}
}
✅ Output: It always returns 2
— finally
overrides any return from try
or catch
.
🔥 Quick Recap
Block | Purpose | Runs When? |
---|---|---|
try | Risky code | Always |
catch | Handle exception | If exception happens |
finally | Cleanup (closing files, releasing locks) | Always (even if no exception) |
📚 Summary
✅ try-catch-finally
is Java’s main exception handling tool.
✅ finally
is great for cleanup, but try-with-resources
is often better for resources.
✅ finally
almost always runs — except for extreme cases like System.exit()
.
✅ Multiple catch
blocks allow handling different exceptions differently.
✅ A finally
block can override a return (but that’s bad practice).