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 to the logic of your application, allowing us to manage these errors more precisely.

To create a custom exception, it must inherit from the base class Exception (or one of its subclasses).

Defining Custom Exceptions

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

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

It is common to add a constructor that accepts an error message and other relevant parameters. 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 own hierarchy of errors, including inheritance among them.

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

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

Using Custom Exceptions

Once custom exceptions are defined, they can be used in try and except blocks in the same way as built-in exceptions.

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 exceptions.

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")