Built-in Exception Types
Custom exceptions are user-defined classes that inherit from Exception, enabling you to represent errors specific to your application's domain.
When Generic Errors Are Not Enough
Python provides built-in exception types such as ValueError and TypeError for common errors. However, an application can also have problems that are meaningful only within its own domain. A text validator, for example, may need to distinguish input that is too short from other kinds of invalid values. A custom exception gives that situation a name that makes sense in the application.
A custom exception is a user-defined class that inherits from Exception and represents an error specific to an application's domain.
The Exception Inheritance Chain
To define a custom exception, create a class whose parent is Exception. Exception itself inherits from BaseException. This inheritance chain allows the custom exception to work with Python's exception-handling system. Code that catches Exception or BaseException can therefore also catch an exception defined by your application.
The pass statement means that this first version adds no methods or attributes beyond what it inherits from Exception. Even so, ShortInputException now gives the short-input problem its own exception type and can be raised elsewhere in the program.
Attaching Useful Error Details
A custom exception becomes more useful when it carries information about what went wrong. An __init__ method can store relevant values as instance attributes. In the short-input example, the exception stores the actual input length and the minimum length required. The __init__ method also calls Exception.__init__(self) to initialize the parent Exception class.
The length and atleast parameters become attributes on the exception object. Once the exception is caught, the handling code can read those attributes and provide feedback based on the exact details of the error.
Raising and Catching the Custom Type
Validating Minimum Input Length
Validate that text contains at least 3 characters and report the actual length when it does not.
Define the exception: ShortInputException inherits from Exception and accepts the actual length and required minimum as arguments.
Raise the exception: The raise statement creates a ShortInputException object with the actual text length and the required minimum of 3.
Transfer control: When raise executes, control immediately jumps to the nearest enclosing try-except block that can handle the exception type.
Read the details: The except block binds the caught object with as and can access its length and atleast attributes.
The handler can give specific feedback about the actual input length and the minimum length required.
class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = input("Enter text: ") if len(text) < 3: raise ShortInputException(len(text), 3) except ShortInputException as error: print("Input length:", error.length) print("Minimum length:", error.atleast) else: print("Input accepted")
Domain-Specific Handling
The main advantage of a custom exception is not merely its name. It gives the handling code a type that represents a particular application situation. A handler can catch ShortInputException specifically, access its stored details, and provide feedback about the short input rather than treating the problem as an unspecified failure. This makes error handling clearer and more maintainable for developers working with the application.
| General built-in exception | Custom exception |
|---|---|
| Represents a common error category such as ValueError or TypeError | Represents a problem specific to the application's domain |
| May not communicate the application's exact situation | Names the application's exact situation |
| Provides the behavior supplied by Python's built-in type | Can optionally store application-specific details in __init__ |
Mistakes with Custom Exceptions
Defining the custom exception without inheriting from Exception
The source pattern defines the custom exception as a subclass of Exception so that it integrates with Python's exception-handling hierarchy.
Fix:
Write class ShortInputException(Exception):Raising the exception without the arguments required by __init__
The detailed version of ShortInputException expects the actual length and the minimum length as constructor arguments.
Fix:
Provide both values, such as the actual input length and 3.Catching the exception without binding the exception object
Without as and a variable name, the handler does not have the exception object available through that variable for reading its stored attributes.
Fix:
Use a form such as except ShortInputException as error: when the handler needs error.length or error.atleast.Using a generic handler when a domain-specific handler is available
A custom exception is intended to make the application's error situation clearer and support targeted handling.
Fix:
Catch the custom exception type in the relevant except block and use its stored details.
Keep the custom exception focused on representing the domain problem and the information needed by its handler. The source example uses a small class with two attributes: the actual input length and the minimum required length.
Practice the Exception Path
Describe the control flow when the user enters fewer than 3 characters in the short-input validator. Identify the class that is instantiated, the two values passed to it, the block that receives control, and the two attributes available to that block.
Hints
- Follow the condition that checks whether the input length is less than 3.
- Look at the arguments supplied after ShortInputException in the raise statement.
- The except block binds the exception object with as.
What do you think happens?
What happens after the validator executes raise ShortInputException(len(text), 3) for input shorter than 3 characters?
Reveal answer
Answer: Control jumps to the matching except block
The raise statement creates the custom exception with the actual length and the required minimum. Execution stops at that point in the try block and moves to the nearest enclosing handler that can catch ShortInputException.
Key Takeaways
- A custom exception is a user-defined class that inherits from Exception.
- Exception inherits from BaseException, so custom exceptions fit into Python's exception-handling hierarchy.
- The raise statement creates and sends a custom exception, using arguments expected by its __init__ method.
- An __init__ method can store details such as the actual input length and the required minimum.
- An except block can bind the exception object with as and use its stored data for targeted, domain-specific handling.
Key Takeaways
- Custom exceptions name errors that are specific to an application's domain.
- Define one by inheriting from Exception, optionally adding an __init__ method for error details.
- Use raise with the arguments required by the custom exception.
- Catch the custom type in an except block and access its stored attributes through the bound exception object.
- The BaseException to Exception to custom exception hierarchy makes custom exceptions compatible with Python's handling system.