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.
1. What 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.
2. Why 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.
3. Real-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.
4. Syntax
javatry { // risky code } catch (ExceptionType e) { // handle exception } finally { // always runs }
5. Example 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.6. Key Points to Remember
finallyruns whether or not an exception was thrown, and even if thetryblock has areturnstatement.- It's commonly used to release resources, like closing files, database connections, or network connections.
finallyis optional, but when present, it always follows thecatchblock(s).