Intermediate   Chapter 115 · 25 min read · Module 9: Exception Handling

Custom Exceptions

Learning objectives
  • After this chapter you can define a custom exception class.
  • You can add attributes and a custom message to an exception.
  • You can build a hierarchy of exceptions with a common base class.
  • You can catch a group of custom errors by catching their base class.
  • You can decide when a custom exception is worth creating.

Python has many built-in exceptions, but they describe general problems such as a bad value or a missing key. Your own program has its own kinds of problems: an insufficient bank balance, an unknown product code, an expired ticket. Custom exceptions let you give these problems their own names.

A custom exception is just a class that inherits from Exception. It can be a single line long. Even so, it makes code easier to read, because the name InsufficientFundsError says exactly what happened. It also makes handling precise, because callers can catch that one class and ignore everything else.

In this chapter you will write simple and detailed exception classes, store extra information in them, organise them into a family with a base class, and learn some naming and design habits that professional Python code follows.

A minimal custom exception

To create a new exception, write a class that inherits from Exception. You do not need any code inside, so the body can be just a docstring or the word pass. After that, you can raise it and catch it exactly like a built-in error. If you have not met classes yet, think of this as a short recipe: the name goes after class, and the parent goes in brackets.

Custom exception: a class you write, inheriting from Exception, that represents a problem specific to your program
Example 1: the smallest custom exception
class OutOfStockError(Exception):
    pass

def buy(stock, wanted):
    if wanted > stock:
        raise OutOfStockError('only ' + str(stock) + ' left')
    return stock - wanted

try:
    buy(3, 5)
except OutOfStockError as e:
    print('Sorry,', e)
Sorry, only 3 left

Always inherit from Exception or one of its subclasses, not from BaseException. The class BaseException also covers events such as the user pressing Ctrl+C, which ordinary programs should not catch by accident.

Adding data to an exception

An exception is an ordinary object, so it can carry extra information. Write an __init__ method that stores the values in attributes, and call super().__init__(message) so that str(error) still gives a readable message. The code that catches the error can then read the attributes and react in a smart way, for example by showing how much money is missing.

Example 2: attributes on an exception
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__('balance ' + str(balance) + ' is less than ' + str(amount))

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

try:
    withdraw(50, 80)
except InsufficientFundsError as e:
    print(e)
    print('Missing:', e.amount - e.balance)
balance 50 is less than 80 Missing: 30

Building a hierarchy

In a bigger project, create one base exception for the whole package and let all other errors inherit from it. Callers can then catch the single base class to handle every error from your code, or catch a specific subclass for finer control. The standard library does this too: FileNotFoundError and PermissionError both inherit from OSError.

Example 3: a family of errors
class ShopError(Exception):
    pass

class OutOfStockError(ShopError):
    pass

class PaymentError(ShopError):
    pass

for problem in [OutOfStockError('no tea'), PaymentError('card declined'), KeyError('x')]:
    try:
        raise problem
    except OutOfStockError:
        print('stock problem')
    except ShopError as e:
        print('shop problem:', e)
    except Exception:
        print('something else')
stock problem shop problem: card declined something else

Order matters in the except chain. Python checks the clauses from top to bottom and uses the first one that matches. Put the more specific subclass before its parent, otherwise the parent catches everything and the specific clause can never run.

Customising the message

You can give a class a default message by defining __init__ with a default argument, or by overriding __str__. A default message keeps the raise statement short when the situation is obvious.

Example 4: a default message
class InvalidCodeError(ValueError):
    def __init__(self, code, message='code must have 4 digits'):
        self.code = code
        super().__init__(message)

def check_code(code):
    if len(code) != 4 or not code.isdigit():
        raise InvalidCodeError(code)
    return code

try:
    check_code('12a')
except ValueError as e:
    print(type(e).__name__, '-', e)
    print(e.code)
InvalidCodeError - code must have 4 digits 12a

Notice that InvalidCodeError inherits from ValueError, not directly from Exception. When your error is a more precise version of a built-in one, inheriting from the built-in lets old code that catches ValueError keep working.

When to create a custom exception

  • Create one when callers need to tell your error apart from others and handle it differently.
  • Create one when the name makes the code much clearer than a generic ValueError.
  • Do not create one for every small problem. If a built-in class fits well, use it.
  • Name them with the suffix Error, for example ConfigError, and keep them in one module.
Example 5: catching with the base class
class AppError(Exception):
    pass

class ConfigError(AppError):
    pass

class NetworkError(AppError):
    pass

def start(step):
    if step == 1:
        raise ConfigError('missing file')
    if step == 2:
        raise NetworkError('timeout')
    return 'started'

for step in [0, 1, 2]:
    try:
        print(start(step))
    except AppError as e:
        print(type(e).__name__ + ': ' + str(e))
started ConfigError: missing file NetworkError: timeout

Why not just use Exception everywhere?

You could raise a plain Exception('out of stock') every time, but then a caller who wants to handle only that case must catch Exception, which also catches unrelated bugs such as a typing mistake in the code. A named class lets the caller write except OutOfStockError and let every other problem travel upwards, where it belongs. Precise handling is one of the main reasons exceptions exist.

Custom exceptions also act as documentation. When a reader sees raise PaymentError in a function, they immediately know what kind of failure the function can cause. A list of the exception classes in a project is, in a way, a list of everything that can go wrong in it.

Testing and reading custom errors

Remember that an exception class is still a class. You can check isinstance(error, ShopError) to see if an object belongs to a family, use type(error).__name__ to print its class name, and read error.args to get the values passed to the constructor. These small tools are very useful in logging code that handles many different kinds of errors at once.

Custom exceptions are classes, so you will understand them best after the object-oriented chapters. For now, copy the pattern: class Name(Exception) and, when needed, an __init__ that calls super().__init__(message).

Python syntax

Syntax
class MyError(Exception):
    pass
Syntax
class MyError(Exception):
    def __init__(self, value):
        self.value = value
        super().__init__('message about ' + str(value))
Syntax
class AppError(Exception): pass
class SubError(AppError): pass

Real-world applications

  • Banking, shop and booking programs with their own error types.
  • Libraries that expose one base error for all failures.
  • Web frameworks that map errors to HTTP responses.
  • Validation layers that report which field is wrong.

Common mistakes

Mistake: Inheriting from BaseException.
Fix: Inherit from Exception so that Ctrl+C and exit signals are not caught by accident.
Mistake: Forgetting to call super().__init__(message) in a custom __init__.
Fix: Call it so str(error) and error.args still work.
Mistake: Putting the parent class before the subclass in the except chain.
Fix: Order except clauses from most specific to most general.
Mistake: Making a new exception class for every tiny problem.
Fix: Use built-in exceptions when they fit and create custom ones only where they add meaning.

Important tips

  • End class names with Error.
  • Make one base exception per package.
  • Store useful values as attributes.

Key points summary

  • A custom exception inherits from Exception.
  • Extra attributes can be added in __init__.
  • A base class lets you catch a whole family of errors.
  • Specific except clauses go before general ones.

Exam and interview points

  • Custom exceptions should inherit from Exception.
  • issubclass(MyError, Exception) is True.
  • An except clause for a parent class also catches its subclasses.

Quick revision

  • class XError(Exception): pass
  • Add attributes in __init__ and call super().__init__(msg).
  • Base error plus subclasses forms a family.
  • Specific except first.

Frequently asked questions

Do I need to write any code inside a custom exception class?

No. A class with just pass already works and has a message through the inherited constructor.

Why call super().__init__?

It stores the message in args so that print(error) and str(error) show it. Without it the message may be empty.

Should I inherit from ValueError or Exception?

Inherit from ValueError when your error is a special kind of bad value. Otherwise inherit from Exception or from your own base error.

Where should I keep my exception classes?

In one module, often called exceptions.py, so that other files can import them easily.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters