Python Glossary Русский

all Python 3Exceptionsterm

Exception hierarchy

hierarchy

The built-in exceptions form a hierarchy. BaseException → Exception → the standard exceptions.

Syntax

BaseException
  SystemExit, KeyboardInterrupt
  Exception
    ValueError, TypeError, IndexError...

Catch the specific class rather than Exception: a broad handler quietly swallows typos in your own code. SystemExit, KeyboardInterrupt and GeneratorExit inherit straight from BaseException on purpose, so except Exception leaves them alone, while a bare except: grabs them and breaks Ctrl+C. except clauses are tested top to bottom, so a subclass like IndexError must come before its ancestor LookupError or it will never run.

Examples

print([c.__name__ for c in ZeroDivisionError.__mro__])
# → ['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']
print(issubclass(KeyError, LookupError))  # → True
print(issubclass(KeyboardInterrupt, Exception))  # → False
# Базовый класс ловит всех наследников
for action in (lambda: [1, 2][5], lambda: {}['missing']):
    try:
        action()
    except LookupError as e:
        print(type(e).__name__)  # → IndexError, затем KeyError
for bad in (lambda: int('abc'), lambda: 'str' + 1, lambda: None.attr):
    try:
        bad()
    except Exception as e:
        print(type(e).__name__)  # → ValueError / TypeError / AttributeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy