14 02 Finally

This lesson continues the discussion on Java exceptions and introduces the finally keyword. When an exception is thrown inside a try block, control jumps to the matching catch block. Imagine, however, that we want to run some piece of code whether an exception was thrown or not. That is exactly what the finally clause is for.

Take a simple ArithmeticException example. After the try and the catch we add a finally block that prints "coucou". When the program runs, the message is printed in every case, both when the exception is caught and when no exception happens at all. The finally block is executed no matter what.

Why finally matters

The most common reason to use finally is to make sure resources are released. A typical case is closing a file that was opened in the try block. If we do not close it inside finally, an exception in the middle of reading would leave the file handle open. By placing close() in finally, the file is always closed, even when something goes wrong.

  • try contains the code that may throw.
  • catch handles the exception when it is thrown.
  • finally runs in both cases and is ideal for cleanup.

This pattern is so important that we will rely on it in the next lessons when we start working with files. Compile and run the small example to see finally in action, and we will continue with the try/catch family in the next lesson.

Summary

The finally keyword in Java executes code unconditionally regardless of whether an exception is thrown or caught in a try-catch block. This lesson covers how the finally block works in exception handling and introduces its primary use case: ensuring cleanup operations like closing files always run. Understanding finally is essential for reliable resource management in Java applications.

Key points

  • The finally block executes whether an exception occurs or is caught—it runs 'no matter what'
  • Finally is part of the try-catch-finally control structure and comes after both try and catch blocks
  • Common use case: ensuring files are closed and resources are properly released, even if an exception happens
  • Finally guarantees that critical cleanup code is never skipped due to exception flow
  • The finally keyword is fundamental for resource management and will be essential when working with file handling

FAQ

What is the purpose of the finally keyword in Java?

The finally keyword allows you to execute code that must run regardless of whether an exception is thrown or caught. It ensures critical operations, such as closing files, always complete.

Does finally execute if an exception is caught?

Yes, the finally block always executes after the try-catch blocks, whether or not an exception occurs or is caught.

When should I use finally?

Use finally when you need to guarantee cleanup code runs in all scenarios, especially for resource management like closing files or releasing system resources.