1. Introduction
The else clause of a try statement lets you specify code that should run only if the try block completed without raising any exception. It sits after all except clauses and before an optional finally clause, giving you a place to put code that depends on the try block having succeeded, without accidentally catching exceptions that code itself might raise.
Cricket analogy: The else clause is like a victory lap that only happens if the chase is completed without a collapse—it runs after all the risky overs (try) and wicket reviews (except), keeping the tense chase separate from the celebration.
This distinguishes 'code that might fail' (in try) from 'code that should only run on success' (in else), keeping the try block minimal and making it clear which statements are actually being protected by the except handlers.
Cricket analogy: Keeping the try block to just "facing the delivery" and putting the celebration in else is like a batsman only worrying about survival during the ball, then celebrating a milestone separately—clearly showing which action was actually risky.
2. Syntax
try:
value = risky_operation()
except SomeError as e:
handle(e)
else:
use(value) # runs only if try succeeded, no exception raised
finally:
cleanup() # always runs3. Explanation
The key distinction between else and finally is when each runs: else runs only when the try block did NOT raise an exception, while finally always runs, whether or not an exception occurred. If the try block raises an exception that is caught, the else clause is skipped entirely, but finally still executes.
Cricket analogy: else is like a victory speech given only if the team wins without needing DRS drama, while finally is like the post-match handshake that happens regardless of the result—even a rain-affected abandoned match still gets the handshake.
A common reason to use else instead of just adding more lines to try is to avoid accidentally catching exceptions raised by the 'success path' code itself. If you put use(value) inside the try block instead of else, and use(value) happens to raise the same type of exception being caught (e.g. SomeError), it would be mistakenly handled by the except clause as if the original operation had failed.
The full ordering of a try statement is: try, then except clause(s), then an optional else, then an optional finally. else cannot appear without at least one except clause. When all four are present, execution order on success is: try body runs fully, no exception, else runs, then finally runs.
Cricket analogy: The full sequence—try the chase, except a collapse, else celebrate, finally shake hands—can't skip the "except" step, just as a team can't have a victory-lap plan without first having a contingency plan for a collapse.
4. Example
def parse_and_use(text):
try:
number = int(text)
except ValueError as e:
print(f"except: could not parse '{text}': {e}")
else:
print(f"else: parsed successfully, number = {number}")
print(f"else: doubled = {number * 2}")
finally:
print("finally: parse_and_use done\n")
parse_and_use("42")
parse_and_use("not-a-number")5. Output
else: parsed successfully, number = 42
else: doubled = 84
finally: parse_and_use done
except: could not parse 'not-a-number': invalid literal for int() with base 10: 'not-a-number'
finally: parse_and_use done
6. Key Takeaways
- else runs only when the try block completes without raising any exception.
- finally always runs regardless of whether an exception occurred; else does not.
- else must follow at least one except clause; it cannot appear alone with try.
- Putting success-path code in else avoids accidentally catching its own exceptions in the except block.
- Execution order is: try, except (if raised), else (if no exception), then finally.
- else keeps the try block focused strictly on the code that might actually fail.
Practice what you learned
1. When does the else clause of a try statement execute?
2. What is the main difference between else and finally?
3. Can you write a try/else block with no except clause?
4. Why might you move success-path code from try into else?
5. In `parse_and_use("not-a-number")` from the lesson, which clauses execute?
Was this page helpful?
You May Also Like
try-except in Python
How to use try-except blocks to catch and handle exceptions gracefully, including catching multiple exception types.
finally Block in Python
How the finally clause guarantees cleanup code runs no matter what happens in a try block, including with return and break.
Exceptions in Python
What exceptions are, how Python's built-in exception hierarchy is structured, and how errors propagate through a program.
Custom Exceptions in Python
How to define your own exception classes to represent domain-specific errors, and how to raise and chain them properly.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics