Try
Python · Exception Handling
Theory
The try block marks code that might raise an exception. Python runs it line by line as usual; if every line succeeds, the except blocks are skipped. The moment one line raises an exception, the rest of the try block is skipped and Python looks for an except clause whose type matches the error.
In the example, 10 / 0 raises ZeroDivisionError, so result is never assigned and control jumps to except ZeroDivisionError, which prints a message. A try must be followed by at least one except or a finally. Only exceptions raised inside the try block (including inside functions it calls) are handled; an error raised inside an except or finally block is not caught by the same statement. Keep the try block small so you catch only the failure you expect.
Why we use it
It marks exactly which code is risky, so the program can recover from a predictable failure - a bad value, a missing file - instead of stopping with a traceback.
When to use it
Wrap the specific lines that depend on outside conditions: conversions, file and network calls, division by user-provided numbers. Do not wrap large blocks 'just in case'; that hides bugs and makes errors hard to trace.
How it works
- Enter the try block
- Run the next line
- Did this line raise? Yes: Skip rest of try, find matching except. No: Continue to the next line.
- Matching except found? Yes: Run that except block. No: Exception propagates to the caller.
- Continue after the try statement
Syntax
try:
risky_code()Example
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")Key points
- Always paired with at least one except block (or a finally)
- Only the try block's code is monitored, not the except/finally code
- Execution leaves try at the first failing line
- Errors from functions called inside try are caught too
- Keep try blocks as small as possible