An except clause only runs if the exception raised in the try block matches, or is a subclass of, the type it names; unmatched exception types skip past it and continue looking for a later except clause, or propagate up if none match. You can catch multiple exception types in one clause by listing them in a tuple, and capture the exception object itself with an `as` clause to inspect its message or arguments. Multiple except clauses are checked in order, top to bottom, and only the first matching one runs.
1Understanding except Block
An except clause only runs if the exception raised in the try block matches, or is a subclass of, the type it names; unmatched exception types skip past it and continue looking for a later except clause, or propagate up if none match. You can catch multiple exception types in one clause by listing them in a tuple, and capture the exception object itself with an as clause to inspect its message or arguments. Multiple except clauses are checked in order, top to bottom, and only the first matching one runs.
Avoid a bare except with no exception type — it catches everything, including KeyboardInterrupt and SystemExit, which can make a program impossible to stop cleanly and hides bugs you never intended to catch.
try:
value = int("not a number")
except ValueError as e:
print(f"Conversion failed: {e}")2Practical Example
Here is a real-world application of except Block showing how it is used in production Python code.
try:
data = {"a": 1}
print(data["b"])
except (KeyError, IndexError):
print("Item not found")3Best Practices
Follow these guidelines when working with except Block:
1. Catch specific exception types instead of a bare except, so unexpected bugs aren't silently swallowed
2. Order except clauses from most specific to most general, since a broader parent exception type placed first would shadow more specific ones below it
3. Use except SomeError as e: to inspect the exception's message when you need to log it or include it in your own error handling
Tip: Avoid a bare except with no exception type — it catches everything, including KeyboardInterrupt and SystemExit, which can make a program impossible to stop cleanly and hides bugs you never intended to catch.
try:
value = int("not a number")
except ValueError as e:
print(f"Conversion failed: {e}")