Except
Python · Exception Handling
Theory
An except clause says which exception types to handle and what to do. except ValueError: catches only ValueError (and its subclasses); except (ValueError, TypeError): catches either; except ValueError as e: also binds the exception object to e, so print(e) shows its message, such as "invalid literal for int() with base 10: 'abc'".
You can stack several except blocks after one try. Python checks them top to bottom and runs only the first one that matches, so put specific exceptions before general ones like Exception. If none match, the exception continues up to the caller. A bare except: catches everything, including KeyboardInterrupt and SystemExit, so it can hide real bugs; if you must catch broadly, use except Exception as e and log the error.
Why we use it
Different failures need different responses: bad input might be re-asked, a missing file created, a network error retried. except lets you match each error type to its own recovery.
When to use it
Catch the specific exceptions you can actually handle. Let unexpected exceptions propagate (or log and re-raise them with raise) so bugs stay visible instead of being silently swallowed.
How it works
- An exception is raised in try
- Check the first except clause
- Does the exception type match? Yes: Run this except block. No: Check the next except clause.
- Any except clauses left? Yes: Repeat the type check. No: Exception propagates to the caller.
- Program continues after the try statement
Syntax
except ExceptionType as e:
handle(e)Example
try:
x = int('abc')
except ValueError as e:
print(f'Invalid input: {e}')Key points
- Catch specific exception types rather than a bare except when possible
- Multiple except blocks can handle different error types differently
- Order matters: put specific types before general ones
- except (A, B): handles several types in one block
- Use raise alone inside except to re-raise after logging