Built-in Exception Types
A custom exception is a user-defined class that inherits from Exception and represents an error specific to an application's domain.
Try it: try / except / else / finally
How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.
How it works
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- finally runs in every case.
Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.
Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.
Loading the simulation…
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.
- 1Define the exception
ShortInputExceptioninherits from Exception and accepts the actual length and required minimum as arguments. - 2Raise the exception
The raise statement creates a
ShortInputExceptionobject with the actual text length and the required minimum of 3. - 3Transfer control
When raise executes, control immediately jumps to the nearest enclosing try-except block that can handle the exception type.
- 4Read 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")- 1The program defines
ShortInputExceptionas a subclass of Exception. - 2The try block reads input and checks its length.
- 3For input shorter than 3 characters, raise creates a
ShortInputExceptionand execution stops at that point in the try block. - 4The matching except block receives the exception object and reads
error.lengthand error.atleast. - 5For input with 3 or more characters, no exception is raised and the else block confirms successful input.
- The class stores the actual length and the required minimum.
- The validation condition checks whether the input is shorter than 3 characters.
- raise creates the custom exception with the two required arguments.
- as error binds the caught exception object to the name error.
- The handler reads the stored attributes.
- The else block runs when the input is at least 3 characters.
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__ |
Custom exceptions extend Python's exception-handling system with domain-specific meaning.
Mistakes with Custom Exceptions
Common mistake Defining the custom exception without inheriting from Exception
What it looks likeclass ShortInputException: passWhy it failsThe source pattern defines the custom exception as a subclass of Exception so that it integrates with Python's exception-handling hierarchy.
Do this insteadWrite class ShortInputException(Exception):Common mistake Raising the exception without the arguments required by __init__
What it looks likeraise ShortInputException()Why it failsThe detailed version of
ShortInputExceptionexpects the actual length and the minimum length as constructor arguments.Do this insteadProvide both values, such as the actual input length and 3.
Common mistake Catching the exception without binding the exception object
What it looks likeexcept ShortInputException:Why it failsWithout as and a variable name, the handler does not have the exception object available through that variable for reading its stored attributes.
Do this insteadUse a form such as except ShortInputException as error: when the handler needs error.length or error.atleast.
Common mistake Using a generic handler when a domain-specific handler is available
Why it failsA custom exception is intended to make the application's error situation clearer and support targeted handling.
Do this insteadCatch 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
ShortInputExceptionin 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
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
- 1A custom exception is a user-defined class that inherits from Exception.
- 2Exception inherits from
BaseException, so custom exceptions fit into Python's exception-handling hierarchy. - 3The raise statement creates and sends a custom exception, using arguments expected by its
__init__method. - 4An
__init__method can store details such as the actual input length and the required minimum. - 5An except block can bind the exception object with as and use its stored data for targeted, domain-specific handling.
At a glance
- 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
BaseExceptionto Exception to custom exception hierarchy makes custom exceptions compatible with Python's handling system.