Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 149 ยท Files and Errors

Custom Exceptions

Create your own exception classes in Python by subclassing Exception, add extra data, design an exception hierarchy, and handle exception groups with except*.

Built-in exceptions like ValueError and KeyError cover a lot of ground, but they describe problems in general terms. When you write a bank account module, "insufficient funds" is a very specific situation, and code that uses your module may want to handle it differently from any other ValueError. That's what custom exceptions are for.

Defining your own exception takes two lines of code. In this lesson you'll create exception classes, give them extra information, group them into a hierarchy so callers can catch a whole family at once, and take a brief look at exception groups, which bundle several errors together.

Your first custom exception

An exception type is a class, and a custom exception is a class that inherits from Exception. You'll learn classes properly in Classes and Objects; for now, this pattern is all you need:

Python Defining and raising a custom exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The class body is just a docstring. That's enough: the class inherits everything from Exception, including accepting a message and printing it in tracebacks. Some people write pass instead of a docstring, but a one-line description is more helpful.

Two naming conventions are worth following:

  • End the name with Error, like the built-ins (ValueError, KeyError).
  • Inherit from Exception, never from BaseException. BaseException is the root of all exceptions, including KeyboardInterrupt and SystemExit, which are meant to stop the program and shouldn't be caught by ordinary except Exception: handlers.

Adding extra data

A message is text for humans. Code that handles an exception often needs structured details, such as the amount that was missing. You can store them as attributes by giving your exception an __init__ method:

Python An exception with attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The important line is super().__init__(message). It passes the message up to Exception, which stores it so that str(error) and the traceback show it. Without that call, the message would be missing.

Tip: if your exception only needs a couple of extra fields, you can skip a custom __init__, pass them as extra positional arguments (raise PaymentError("declined", 402)) and read them back from error.args. The printed message then shows the whole tuple, though, and named attributes like error.shortfall are much clearer to the code that catches the error.

Building an exception hierarchy

Libraries usually define one base exception for the whole package and derive the specific ones from it. Callers can then choose how precise to be: catch one specific error, or catch everything your library raises with a single clause, without accidentally catching unrelated errors.

Python A small hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few things to notice:

  • OutOfStockError is handled by its own clause. UnknownProductError falls through to the general ShopError clause, because it's a subclass of ShopError.
  • UnknownProductError inherits from both ShopError and KeyError. Code that already catches KeyError for missing items keeps working, while new code can catch ShopError. This "also a built-in" trick is common in well-designed libraries.
  • Order matters: specific clauses must come before the general base-class clause, or the base class would catch everything first.

When should you create one?

Custom exceptions are useful, but not every error needs its own class. A quick checklist:

  • Use a built-in when one describes the problem exactly. A function that requires a positive number should raise ValueError; callers expect that.
  • Create a custom exception when callers will want to catch this specific situation separately, when you need to attach structured data, or when you're writing a module or library and want a base class for all its errors.
  • Don't go overboard. A dozen nearly identical exception classes make code harder to use, not easier. Start with a base class and one or two specific ones; add more when a real need appears.

Exception groups (brief)

Normally only one exception is in flight at a time. But some code runs several tasks at once, such as validating every field of a form or running concurrent network requests, and more than one of them can fail. Python 3.11 added ExceptionGroup to raise several exceptions together, and the except* syntax to handle the members of a group by type:

Python ExceptionGroup and except*

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Unlike ordinary except, every matching except* clause runs: one for the missing fields and one for the bad age. Each receives a smaller group containing just its matching exceptions, available as group.exceptions. You'll meet exception groups again in Async Programming with asyncio, where task groups use them to report failures from several tasks.

Note: you can't mix except and except* in the same try statement. Exception groups are a Python 3.11+ feature, so older interpreters show a syntax error for except*.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which class should a custom exception normally inherit from?

    Inherit from Exception or one of its subclasses. BaseException also covers KeyboardInterrupt and SystemExit, which ordinary handlers shouldn't catch.
  2. 2. Your exception defines init with extra attributes. Why call super().init(message)?

    Exception stores its arguments in args and uses them for the message. Skipping the call leaves the message empty.
  3. 3. ParseError inherits from AppError. Which clause catches a ParseError?

    An except clause matches the named class and all its subclasses, so a base class catches its whole family.
  4. 4. What is special about except* compared with except?

    except* splits an ExceptionGroup by type, and each matching clause handles its share of the group.

Summary

  • A custom exception is a class that inherits from Exception: class PaymentError(Exception): """...""".
  • Name it with an Error suffix and never inherit from BaseException.
  • Add attributes in __init__ and call super().__init__(message) so the message still works.
  • Build a hierarchy: one base exception per module or library, with specific subclasses; a subclass can also inherit from a built-in like KeyError.
  • Prefer built-in exceptions when they fit; create custom ones when callers need to catch the case separately.
  • ExceptionGroup bundles several exceptions, and except* handles each type in the group (Python 3.11+).

Next: Context Managers, where you'll see how the with statement works and write your own.