Packages & Exception Handling · Lesson 67 of 150
finally
finally is a block that runs after a try-catch, regardless of whether an exception occurred or not. It's typically used for cleanup work, like closing a file or a database connection.
01What is finally?
finally is a block that runs after a try-catch, regardless of whether an exception occurred or not. It's typically used for cleanup work, like closing a file or a database connection.
02Why is it used?
Certain cleanup actions must happen no matter what — whether the risky code succeeded or failed. finally guarantees this cleanup code always runs, avoiding resource leaks like an open file being left unclosed.
03Real-Life Example
Think of turning off the stove after cooking, whether the dish turned out perfectly or got burnt. That final step (turning off the stove) always happens regardless of the outcome — just like a finally block.
04Syntax
javatry { // risky code } catch (ExceptionType e) { // handle exception } finally { // always runs }
05Example Program
javapublic class FinallyDemo { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Error occurred!"); } finally { System.out.println("Cleanup complete."); } } }
Output:
Error occurred!
Cleanup complete.