Code placed in a try/except's else clause runs only after the try block finishes successfully, with no exception raised — if any exception occurred and was caught, the else block is skipped entirely. This lets you separate 'the code that might fail', in try, from 'the code that should only run on success', in else, which is clearer than just adding more code to the end of the try block, since that would also be caught by an except if it happened to raise the same exception type by coincidence.
1Understanding else Block (Exceptions)
Code placed in a try/except's else clause runs only after the try block finishes successfully, with no exception raised — if any exception occurred and was caught, the else block is skipped entirely. This lets you separate 'the code that might fail', in try, from 'the code that should only run on success', in else, which is clearer than just adding more code to the end of the try block, since that would also be caught by an except if it happened to raise the same exception type by coincidence.
Putting success-only code in else instead of at the end of the try block avoids accidentally catching an exception from that success code as if it came from the risky operation you were actually trying to guard.
try:
number = int("42")
except ValueError:
print("Not a valid number")
else:
print(f"Parsed successfully: {number}")2Practical Example
Here is a real-world application of else Block (Exceptions) showing how it is used in production Python code.
try:
f = open("config.txt")
except FileNotFoundError:
print("Config file missing, using defaults")
else:
print("Config loaded")
f.close()3Best Practices
Follow these guidelines when working with else Block (Exceptions):
1. Use an else clause for code that should run only on success, so it isn't accidentally covered by the try's except handlers
2. Keep the try block itself limited to just the operation that can fail, moving follow-up logic into else
3. Avoid overusing else here if it doesn't add clarity — sometimes just continuing after the try/except is simpler and equally correct
Tip: Putting success-only code in else instead of at the end of the try block avoids accidentally catching an exception from that success code as if it came from the risky operation you were actually trying to guard.
try:
number = int("42")
except ValueError:
print("Not a valid number")
else:
print(f"Parsed successfully: {number}")