Concepts / Built-in Exception Types

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.

  • Programming
Interactive lab

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

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. 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.

Educational simulation

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.

Key point

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.

BaseExceptionExceptionShortInputExceptionuser-defined classinherits frominherits from
What contains what when a custom exception class inherits from the built-in Exception class?
python

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.

python

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.

ShortInputExceptionexception objectlengthactual input lengthexcept blocktargeted handlingatleastrequired minimumstoresstoresread by
What information can the handler read after the custom exception stores details about the invalid input?

Raising and Catching the Custom Type

Worked example

Validating Minimum Input Length

Validate that text contains at least 3 characters and report the actual length when it does not.

  1. 1
    Define the exception

    ShortInputException inherits from Exception and accepts the actual length and required minimum as arguments.

  2. 2
    Raise the exception

    The raise statement creates a ShortInputException object with the actual text length and the required minimum of 3.

  3. 3
    Transfer control

    When raise executes, control immediately jumps to the nearest enclosing try-except block that can handle the exception type.

  4. 4
    Read the details

    The except block binds the caught object with as and can access its length and atleast attributes.

Result

The handler can give specific feedback about the actual input length and the minimum length required.

Code walkthrough
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")
  1. 1
    The program defines ShortInputException as a subclass of Exception.
  2. 2
    The try block reads input and checks its length.
  3. 3
    For input shorter than 3 characters, raise creates a ShortInputException and execution stops at that point in the try block.
  4. 4
    The matching except block receives the exception object and reads error.length and error.atleast.
  5. 5
    For 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.
textuser inputlength < 3validationraiseShortInputExceptionexcept blocktargeted handlerelse blockaccepted inputvalidateyescontrol jumpsno
How does control flow change when raise creates and sends a custom exception with arguments?

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.

input validatordetects short inputShortInputExceptionlength and atleastexcept blockreads exception dataspecific feedbackactual and minimum lengthsraise with detailscaught by typeuses attributes
How does a domain-specific exception move from the point where an error occurs to the code that handles it?
General built-in exceptionCustom exception
Represents a common error category such as ValueError or TypeErrorRepresents a problem specific to the application's domain
May not communicate the application's exact situationNames the application's exact situation
Provides the behavior supplied by Python's built-in typeCan 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 like
    class ShortInputException:
        pass
    Why it fails

    The source pattern defines the custom exception as a subclass of Exception so that it integrates with Python's exception-handling hierarchy.

    Do this instead
    Write class ShortInputException(Exception):
  • Common mistake

    Raising the exception without the arguments required by __init__

    What it looks like
    raise ShortInputException()
    Why it fails

    The detailed version of ShortInputException expects the actual length and the minimum length as constructor arguments.

    Do this instead

    Provide both values, such as the actual input length and 3.

  • Common mistake

    Catching the exception without binding the exception object

    What it looks like
    except ShortInputException:
    Why it fails

    Without as and a variable name, the handler does not have the exception object available through that variable for reading its stored attributes.

    Do this instead

    Use 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 fails

    A custom exception is intended to make the application's error situation clearer and support targeted handling.

    Do this instead

    Catch the custom exception type in the relevant except block and use its stored details.

Best practice

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

MEDIUM

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?

  • The else block executes immediately

  • Control jumps to the matching except block

  • The custom class is ignored because it is not built in

  • The input is automatically changed to contain 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

  1. 1
    A custom exception is a user-defined class that inherits from Exception.
  2. 2
    Exception inherits from BaseException, so custom exceptions fit into Python's exception-handling hierarchy.
  3. 3
    The raise statement creates and sends a custom exception, using arguments expected by its __init__ method.
  4. 4
    An __init__ method can store details such as the actual input length and the required minimum.
  5. 5
    An 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 BaseException to Exception to custom exception hierarchy makes custom exceptions compatible with Python's handling system.

Related concepts

More concepts starting with B