Your First Steps in Python: A Beginner to Intermediate Guide

Raising Your Own Exceptions: Customizing Error Signals

Section 6

Error Handling and Debugging

Your First Steps in Python: A Beginner to Intermediate GuideError Handling and Debugging

As you delve deeper into Python programming, you'll encounter situations where the built-in exceptions don't perfectly capture the specific error conditions your program might face. This is where raising your own exceptions comes in handy. Custom exceptions allow you to signal distinct error types, making your code more readable, maintainable, and easier to debug. Think of them as creating your own specialized warning signs for your program.

The fundamental way to create a custom exception is by defining a new class that inherits from the base Exception class or one of its subclasses. This simple inheritance allows your new class to behave like any other exception in Python, meaning it can be raised and caught.

class NegativeValueError(Exception):
    """Custom exception raised when a value is unexpectedly negative."""
    pass

In this example, we've defined NegativeValueError. It doesn't have any special methods or attributes beyond what it inherits from Exception, but it serves as a unique identifier for a specific type of error.

Now, let's see how we can raise this custom exception when a certain condition is met. We'll use the raise keyword, just as you would with built-in exceptions.

def process_positive_number(number):
    if number < 0:
        raise NegativeValueError("Input number cannot be negative.")
    # Proceed with processing the positive number
    print(f"Processing number: {number}")

In the process_positive_number function, if the input number is less than zero, we raise our custom NegativeValueError with a descriptive message. This message can provide crucial context for debugging.

Catching your custom exceptions works exactly like catching built-in ones. You use a try...except block.

チャプターへ戻る