iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

ExceptionTrigger
ValueErrorRight type, wrong value (int('abc')).
TypeErrorWrong type ('a' + 1).
KeyErrorMissing dict key.
IndexErrorOut-of-range list index.
FileNotFoundErrorOpen missing file.
PermissionErrorOS denied the operation.
TimeoutErrorNetwork or system call timed out.
StopIterationIterator exhausted (don't catch in user code).
AssertionErrorassert 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 :

Test yourself

Q1. Catch-all that still allows Ctrl+C is…
Q2. "Right type, wrong value" raises…
Q3. ExceptionGroup support arrived in Python…

Discussion

Loading…