Python's exception handling doesn't stop at just try
and except
. Two additional blocks—finally
and else
—provide more control and structure to how your program handles errors and cleanup operations.
In this tutorial, you’ll learn when and how to use finally
and else
to make your Python code more robust, readable, and reliable.
1. The finally
Block
The finally
block always runs, no matter what. It executes whether or not an exception was raised and whether or not it was handled. This is ideal for cleanup actions like closing files or releasing resources.
Syntax:
try:
# risky code
except SomeError:
# handle error
finally:
# this code always runs
Example 1: Using finally
to close a file
try:
file = open("sample.txt", "r")
data = file.read()
print(data)
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file (simulated).")
Output: Even if the file doesn't exist, the finally
block runs.
Example 2: finally
without exception
try:
result = 10 / 2
print("Result:", result)
finally:
print("Finished calculation.")
2. The else
Block
The else
block runs if—and only if—no exceptions occur in the try
block. It’s useful when you want to execute code only when everything goes right.
Syntax:
try:
# code that might raise error
except SomeError:
# handle error
else:
# runs only if no error occurs
Example 3: Using else
to confirm success
try:
value = int("42")
except ValueError:
print("Invalid input.")
else:
print("Conversion successful:", value)
Output: Conversion successful: 42
Example 4: Both else
and finally
try:
number = int("100")
except ValueError:
print("Error occurred.")
else:
print("Valid input:", number)
finally:
print("End of program.")
All blocks work together—else
runs only if there’s no exception, and finally
runs no matter what.
3. Common Use Cases
finally
: Releasing resources, closing files, or stopping timers.else
: Code that should only run when thetry
block was successful.
4. Summary Table
Block | When It Executes |
---|---|
try |
When running potentially risky code |
except |
If an exception occurs in the try block |
else |
Only if the try block succeeds without error |
finally |
Always, regardless of whether an error occurred |
5. Final Thoughts
Using finally
and else
makes your exception handling more complete and expressive. finally
ensures essential cleanup happens no matter what, while else
keeps your success path separate from error-handling logic. Together, they help you write safer and more maintainable code.