100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

try-except in Python

How to use try-except blocks to catch and handle exceptions gracefully, including catching multiple exception types.

Exception HandlingBeginner10 min readJul 7, 2026
Analogies

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

python
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

python
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

text
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 e to access the exception instance's message and attributes.
  • If no exception occurs, all except blocks are skipped entirely.

Practice what you learned

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#TryExceptInPython#Try#Except#Syntax#Explanation#ErrorHandling#StudyNotes#SkillVeris