Exception Types
The standard exception hierarchy. Catch the most specific class that fits — vague except Exception hides bugs.
The big tree
BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception ← almost everything you write catches this or a subclass
├── ArithmeticError
│ ├── ZeroDivisionError
│ ├── OverflowError
│ └── FloatingPointError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── ValueError
├── TypeError
├── AttributeError
├── ImportError
│ └── ModuleNotFoundError
├── OSError
│ ├── FileNotFoundError
│ ├── PermissionError
│ └── TimeoutError
├── RuntimeError
│ └── RecursionError
├── StopIteration
├── NameError
│ └── UnboundLocalError
└── SyntaxError
The ones you'll catch most
| Exception | Trigger |
|---|---|
ValueError | Right type, wrong value (int('abc')). |
TypeError | Wrong type ('a' + 1). |
KeyError | Missing dict key. |
IndexError | Out-of-range list index. |
FileNotFoundError | Open missing file. |
PermissionError | OS denied the operation. |
TimeoutError | Network or system call timed out. |
StopIteration | Iterator exhausted (don't catch in user code). |
AssertionError | assert failed. |
Your own exceptions
PYTHON
class PaymentDeclined(Exception):
"""Raised when the card processor rejects a charge."""
raise PaymentDeclined('Card expired')
Exception groups (3.11+)
PYTHON
try:
raise ExceptionGroup('multi', [ValueError('a'), TypeError('b')])
except* ValueError as eg:
print('value:', eg.exceptions)
except* TypeError as eg:
print('type:', eg.exceptions)
Tip: Don't catch
BaseException — it swallows KeyboardInterrupt and SystemExit too. Catch Exception (or a subclass) and let the others propagate.Example
Example
# Common exceptions:
# ValueError, TypeError, KeyError, IndexError,
# FileNotFoundError, ZeroDivisionError, AttributeError,
# StopIteration, ImportError, RuntimeError.
for cls in (ValueError, TypeError, KeyError, IndexError):
print(cls.__name__)
Try it Yourself »
Exercise
Exception type for missing dict key.
except
:
Eight letters; PascalCase.
Discussion
Loading…