Python Reference ยท Exceptions
Custom exceptions
Reference for custom exceptions in Python: subclass Exception, build a small hierarchy, carry extra data, choose a good base class and name them well.
A custom exception is a class that inherits from Exception (or from one of its subclasses). It lets callers catch a problem that belongs to your own code, such as an unpaid invoice or an unknown product, without also catching unrelated errors like a typo that raised AttributeError.
Most custom exceptions are two lines long. You only add code when the exception should carry data, such as an error code or the offending value, or format its own message.
class PaymentError(Exception): """Base class for everything that can go wrong while paying."""
Try it
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.
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.
Defining an exception
Inherit from Exception
Always inherit from Exception, not from BaseException. BaseException is the root for control-flow signals such as KeyboardInterrupt and SystemExit, and a plain except Exception: is expected to leave those alone.
Pick a specific parent when one fits
If your error is a special kind of bad value, inherit from ValueError. If it is a special missing key, inherit from KeyError. Callers who already catch the built-in type then catch yours too. Multiple inheritance, as in UnknownProduct(ShopError, KeyError) above, works when you want both a family and a built-in type.
Make one base class per library or package
A single base such as ShopError gives callers a safe way to say "anything from this library": except ShopError:. Specific subclasses let them handle individual cases first.
Carry data in attributes
Store what a handler needs (error.product, error.available) as attributes instead of making callers parse the message text. Pass a readable message to super().__init__() so str(error) and tracebacks are useful. error.args holds whatever you passed to the base constructor.
Usage notes
- Naming. End the class name with
Errorwhen it describes a fault (ConfigError,ParseError). Names likeOutOfStockare fine for conditions that read naturally without the suffix; the standard library uses both styles (StopIteration,TimeoutError). - Docstring or
pass. An exception class needs no body. A docstring is a good body: it documents when the exception is raised. - Custom
__init__. If your__init__takes arguments that you do not pass tosuper().__init__(),argswill not contain them, and copying or pickling the exception can break. Passing the message through, as the example does, avoids most trouble. - Raise with context. Use
raise MyError(...) from originalto keep the underlying cause visible in the traceback;raise ... from Nonehides it on purpose. - Do not catch too much. Catch the narrowest class that matches what you can actually handle. A bare
except:orexcept Exception:hides your own bugs. - Do not overuse them. If a built-in exception describes the problem exactly (
ValueError,TypeError), raise that. Create a new class when callers need to tell your failure apart from others. - Exception groups. Custom exceptions work with
ExceptionGroupandexcept*like any other exception (Python 3.11 and later). - Notes. Since Python 3.11 you can attach extra context with
error.add_note("text"); notes print under the message in tracebacks.