Language: EN

python-excepciones-personalizadas

Creating Custom Exceptions in Python

In Python, in addition to handling built-in exceptions, we can also define our own custom exceptions.

This is useful because we can represent specific errors related to the logic of your application, providing more precise error handling.

These exceptions must inherit from the base class Exception, or one of its subclasses.

Defining Custom Exceptions

To create a custom exception, we simply define a new class that inherits from Exception.

It is common to add a constructor that accepts an error message and other relevant parameters.

For example,

class MyCustomException(Exception):
    def __init__(self, message):
        super().__init__(message)

We can also add any number of additional parameters we need,

class ValidationError(Exception):
    def __init__(self, field, message):
        self.field = field
        self.message = message
        super().__init__(f"Error in '{field}': {message}")

# Raise the exception
raise ValidationError("name", "The name cannot be empty.")

Similarly, we can have our hierarchy of errors, with inheritance among them

class ConnectionError(Exception):
    def __init__(self, message):
        super().__init__(message)

class TimeoutError(ConnectionError):
    def __init__(self, duration):
        self.duration = duration
        super().__init__(f"Timeout exceeded: {duration} seconds")

Using Custom Exceptions

Once custom exceptions are defined, they can be used in try and except blocks just like built-in exceptions.

For example,

try:
    raise MyCustomException("This is a custom error.")
except MyCustomException as e:
    print(f"My custom exception was caught: {e}")

Additionally, as we saw when discussing the try-except block, we can catch multiple of them

try:
    # Code that may raise an exception
    result = 10 / 0
except MyCustomException:
    print(f"My custom exception was caught: {e}")
except AnotherCustomException:
    print(f"Another custom exception was caught: {e}")
except Exception:
    print("Unknown exception")