Python Try...Except
Python · Tooling & Errors
Theory
When something goes wrong at runtime - dividing by zero, a missing file, bad user input - Python raises an exception, and if nothing handles it the program stops with a traceback. A try/except statement lets you catch it. Code that might fail goes inside try; if an exception occurs, Python stops that block immediately and jumps to the first except whose type matches, such as except ZeroDivisionError.
The full statement has four parts: try (risky code), except (runs on a matching error), else (runs only when no error happened) and finally (always runs, used for cleanup). except ValueError as e gives you the exception object so you can log its message. Catch the specific errors you expect; a bare except: also swallows bugs and even Ctrl+C, hiding real problems.
Why we use it
Programs meet bad data and failing resources all the time. Exception handling lets them respond sensibly - show a friendly message, skip a bad row, retry - instead of crashing halfway through a job.
When to use it
Use try/except around operations that can fail for reasons outside your control: input parsing, file and network access, type conversions. Do not use it to hide bugs; fix logic errors instead of catching them.
How it works
- Enter the try block
- Run the risky code
- Did an exception occur? Yes: Jump to the matching except block. No: Run the else block (if any).
- Run the finally block (always)
- Program continues instead of crashing
Syntax
try:
...
except ExceptionType:
...Example
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')Key points
- finally block always runs, error or not
- Catch specific exception types when possible
- except Error as e gives access to the error message
- An unmatched exception still propagates and stops the program
- Keep the try block small - only the line(s) that can fail