We've explored how try and except blocks help us gracefully handle errors. But what if we want to execute some code only when no exceptions occur, or ensure a piece of code always runs, regardless of whether an error happened? This is where the else and finally clauses come into play in Python's error handling.
The else clause is attached to a try...except block. The code within the else block is executed only if the code within the try block completes successfully without raising any exceptions. Think of it as the 'happy path' – everything went as planned!
try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
# This code runs ONLY if no exception occurred in the try block
print(f"Division successful! Result: {result}")
finally:
print("This will always run.")In the example above, since 10 / 2 does not raise a ZeroDivisionError, the else block will execute, printing "Division successful! Result: 5.0". If the try block had been 10 / 0, the except block would have run, and the else block would have been skipped.
The finally clause is also attached to a try...except block. The code within the finally block is guaranteed to execute, no matter what. This means it will run if:
- The
tryblock completes successfully. - An exception occurs and is caught by an
exceptblock. - An exception occurs and is not caught by any
exceptblock (in this case, thefinallyblock runs before the exception propagates further).