Python finally
The finally keyword in Python is used in alongside try and optionally except blocks. It defines a block of code that is guaranteed to run, no matter what happens in the try block — whether an error occurs or not. This is particularly useful for actions like closing files, releasing resources, or cleaning up after an operation.
Syntax
try:
# Code that may raise an exception
...
except SomeException:
# Code to handle the exception
...
finally:
# Code that will run no matter what
...
In the syntax:
try: Defines the code block to test for errors.except(Optional): Catches and handles specific exceptions.finally: Always runs, regardless of whether an exception occurred.
Example 1: Basic Try-Finally Without Exception
In this example, there is no exception, but the finally block runs regardless:
try:print("Running try block...")finally:print("This will always run.")
Here is the output:
Running try block...This will always run.
Example 2: File Handling with finally
In this example, finally is used to ensure that a file or resource is closed or released even if an error happens during processing:
try:file = open("example.txt", "w")file.write("Hello, World!")except IOError:print("File operation failed.")finally:file.close()print("File closed.")
Here is the output:
File closed.
Codebyte Example: Try-Except-Finally with an Exception
In this codebyte example, an exception occurs, and the except block handles it — but the finally block still runs afterward:
Frequently Asked Questions
1. Can I use finally without an except block?
Yes. finally can be used with just a try block:
try:risky_operation()finally:print("Always executed.")
2. What happens if an exception is not caught but a finally block exists?
The finally block still runs, and the exception is propagated after its execution:
try:1 / 0finally:print("Finally runs before the exception is raised.")
3. Can finally suppress exceptions?
No. The finally block does not suppress exceptions unless it raises another exception or the program exits using sys.exit() or similar. Any exception in the try block will still propagate after the finally block executes.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours