1. Introduction
The try-except statement is Python's primary mechanism for handling exceptions. Code that might fail is placed inside a try block, and code that responds to a specific failure is placed inside one or more except blocks. If no exception occurs, the except blocks are skipped entirely; if an exception does occur, Python stops executing the try block at the point of failure and jumps to the first matching except block.
Cricket analogy: A batter attempting a risky reverse-sweep is like code in a try block — if the shot fails and they're caught, the "except" is the pre-planned response of walking back calmly instead of the innings collapsing into chaos.
This lets a program recover from expected failure modes, such as invalid user input or a missing file, without crashing, and lets the developer decide exactly which errors to handle and how.
Cricket analogy: Just as a team plans a rain-delay contingency instead of forfeiting the match outright, try-except lets a program recover from expected failures like bad input without crashing entirely.
2. Syntax
try:
risky_operation()
except SpecificError as e:
handle_specific(e)
except (TypeError, ValueError) as e:
handle_multiple_types(e)
except Exception as e:
handle_anything_else(e)3. Explanation
A try block can be followed by multiple except clauses, each targeting a different exception type. Python evaluates them in order and executes only the first one whose exception type matches (via isinstance) the exception that was raised. A single except clause can also catch several exception types at once by listing them as a tuple, e.g. except (TypeError, ValueError):.
Cricket analogy: A batter facing a fast bowler might have separate reactions planned for a bouncer, a yorker, or a slower ball — Python checks each except clause in order and reacts with the first matching plan, and a single umpire signal can even cover two related infractions at once, like except (NoBall, Wide):.
The order of except clauses is significant because Python stops at the first match. Since subclasses match their parent class's except clause too, more specific exception types must be listed before more general ones; otherwise the general handler will intercept errors meant for the specific one, and the specific except block becomes unreachable dead code.
Cricket analogy: If the general "any delivery" contingency plan is listed before the specific "yorker" plan, the batter would never actually execute the yorker-specific technique — just as a broad except Exception before a specific except ValueError makes the specific block unreachable.
Placing except Exception: before except ValueError: means the ValueError handler will never run, because Exception matches first. Python does not raise an error for this mistake, so it can silently produce the wrong behavior. Always order except clauses from most specific to most general.
The as e clause binds the exception instance to a name so its message and attributes (like e.args) can be inspected or logged inside the handler.
Cricket analogy: When a run-out appeal fails on review, the third umpire's as e is like binding the specific reason code to a variable so commentators can explain exactly why the decision went the way it did.
4. Example
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
print(f"Cannot divide: {e}")
return None
except TypeError as e:
print(f"Bad types: {e}")
return None
print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide(10, "a"))
try:
int("not a number")
except (TypeError, ValueError) as e:
print(f"Caught combined: {type(e).__name__}: {e}")5. Output
5.0
Cannot divide: division by zero
None
Bad types: unsupported operand type(s) for /: 'int' and 'str'
None
Caught combined: ValueError: invalid literal for int() with base 10: 'not a number'6. Key Takeaways
- try holds code that might fail; except blocks handle specific failure types.
- Python checks except clauses in order and runs only the first matching one.
- Order matters: put specific exception types before general ones like Exception.
- A tuple of types in one except clause catches any of those types.
- Use
as eto access the exception instance's message and attributes. - If no exception occurs, all except blocks are skipped entirely.
Practice what you learned
1. What happens if you place `except Exception:` before `except ValueError:`?
2. How do you catch both TypeError and ValueError in a single except clause?
3. What does `except ZeroDivisionError as e:` do?
4. If code in the try block raises no exception, what happens to the except blocks?
5. In `safe_divide(10, "a")` from the lesson, which except block runs and why?
Was this page helpful?
You May Also Like
Exceptions in Python
What exceptions are, how Python's built-in exception hierarchy is structured, and how errors propagate through a program.
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.
else Clause in Exception Handling
How the try/except/else clause runs code only when no exception occurred, and how it differs from finally.
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