A user-defined exception is a Python class for an exceptional condition specific to your code. Define one by subclassing Exception, then raise and catch it like a built-in exception. Subclass Exception rather than BaseException: a handler for Exception leaves KeyboardInterrupt available to interrupt a try block with Ctrl-C. section 14.2.4 section 14.2.1
Define, raise, and catch one
class MyError(Exception): pass try: raise MyError("Some information about what went wrong") except MyError as error: print("Situation:", error) Output: Situation: Some information about what went wrong Without the handler, the message appears at the end of the traceback. section 14.2.4
The arguments passed when raising the exception remain available to a handler through error.args. For example, raise MyError("Some information", "my_filename", 3) supplies a tuple whose entries can be read as error.args[0], error.args[1], and error.args[2]. An exception class can define its own expectations for arguments, so do not assume every exception treats its first argument as a message. section 14.2.4 section 14.2.2
Choose the scope to fit the program:
- For a small program with a few distinct conditions, subclass Exception directly. section 14.2.4
- For a larger library, define a library-level exception and subclass it for particular conditions. section 14.2.4
- In a package, consider keeping custom exceptions in an exceptions.py module and importing them where needed; __init__.py can expose them at the package level. section 18.6.2
Use one only when the condition warrants it
A text-cleaning function can raise EmptyStringError when line.strip() is empty. That gives the condition its own exception type, but a dedicated class may be unnecessary unless empty strings need particular attention. Built-in exceptions may suit other failures. section 14.4.2


