Skip to content
C

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

java
try { // risky code } catch (ExceptionType e) { // handle exception } finally { // always runs }

5. Example Program

java
public 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

  • finally runs whether or not an exception was thrown, and even if the try block has a return statement.
  • It's commonly used to release resources, like closing files, database connections, or network connections.
  • finally is optional, but when present, it always follows the catch block(s).