finally block in exception handling
✅ The finally
Block in Java
In Java, the finally
block is used with try-catch
to guarantee execution of a block of code regardless of whether an exception occurs or not. It's commonly used for cleanup operations such as closing files, releasing resources, or resetting values.
🔹 Syntax of try-catch-finally
📘 Example 1: Basic Use of finally
Output:
📘 Example 2: No Exception Occurs
Output:
📘 Example 3: Exiting Early with return
Even if you use return
inside try
or catch
, the finally
block will still run.
Output:
✅ Why use finally
?
-
To ensure critical code always executes.
-
To release system resources, e.g., close database connections, file streams.
-
To perform consistent cleanup regardless of program state.
Comments
Post a Comment