finally Block

Cleanup code execution

4 min read

finally Block

The finally block always executes whether an exception occurs or not.

Code Examples

finally always executes

java
1
2try {
3    int[] arr = new int[2];
4    arr[5] = 10;
5} catch (Exception e) {
6    System.out.println("Exception occurred");
7} finally {
8    System.out.println("Cleanup code");
9}
10          

Use Cases

  • Closing resources
  • Cleanup logic

Common Mistakes to Avoid

  • Throwing exceptions in finally
  • Assuming finally won’t execute