Python Glossary Русский

all Python 3Exceptionsterm

Custom exceptions

custom

Write your own exception classes by inheriting from Exception. You can give them attributes and a hierarchy of their own.

Syntax

class MyError(Exception):
    pass

Inherit from Exception, never from BaseException — the latter is home to KeyboardInterrupt and SystemExit, and joining that family means broad handlers start swallowing Ctrl+C and clean shutdown. It pays to define one base error per module or application and derive the specific ones from it: callers can then catch the whole family with a single except, or narrow down to one subclass when they care. Whatever you pass to the constructor lands in args and in str(e) automatically, so a custom __init__ is unnecessary just to carry a message.

Examples

class AppError(Exception):
    pass
class DatabaseError(AppError):
    pass
class NetworkError(AppError):
    pass
try:
    raise DatabaseError('Connection failed')
except AppError as e:
    print(type(e).__name__, e)  # → DatabaseError Connection failed
class ValidationError(ValueError):
    def __init__(self, field, message):
        self.field = field
        super().__init__(f'{field}: {message}')
try:
    raise ValidationError('email', 'invalid format')
except ValidationError as e:
    print(e.field, e)  # → email email: invalid format
class HttpError(Exception):
    def __init__(self, status_code, message):
        self.status_code = status_code
        super().__init__(f'HTTP {status_code}: {message}')
class NotFoundError(HttpError):
    def __init__(self, url):
        super().__init__(404, f'{url} not found')
try:
    raise NotFoundError('/api/users')
except HttpError as e:
    print(e.status_code, e)  # → 404 HTTP 404: /api/users not found
# Иерархия ошибок
class PaymentError(Exception): pass
class InsufficientFundsError(PaymentError):
    def __init__(self, amount, balance):
        self.shortage = amount - balance
        super().__init__(f'Need {self.shortage} more')
try:
    raise InsufficientFundsError(100, 60)
except InsufficientFundsError as e:
    print(e, e.shortage)  # → Need 40 more 40
# raise ... from
class ServiceError(Exception): pass
try:
    try:
        int('abc')
    except ValueError as e:
        raise ServiceError('Parse failed') from e
except ServiceError as e:
    print(e)                    # → Parse failed
    print(type(e.__cause__))   # → <class 'ValueError'>
# repr дефолтный
class SimpleError(Exception):
    pass
e = SimpleError('something went wrong')
print(str(e))   # → something went wrong
print(repr(e))  # → SimpleError('something went wrong')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy