Skip to content
Home / Fundamentals

How to create custom exceptions in Python

Custom exceptions in Python allow you to define your own exception types to handle specific errors or conditions in your code. This can be useful for providing more meaningful error messages to the user, or for handling errors in a specific way in your code.

To create a custom exception in Python, you need to create a new class that inherits from the Exception class. This class should have a init method that takes in any necessary arguments and sets them as attributes of the exception. For example:

class CustomException(Exception):
    def __init__(self, message, code):
        self.message = message
        self.code = code

This custom exception class takes in a message and a code argument and sets them as attributes of the exception. You can then raise this exception using the raise keyword, like this:

raise CustomException("An error occurred", 400)

To catch this custom exception, you can use a try-except block in the same way you would for any other exception. For example:

try:
    # code that might raise the exception goes here
except CustomException as e:
    print(f"Error: {e.message} ({e.code})")

You can also define custom exception classes that inherit from more specific built-in exception classes. For example, if you wanted to create a custom exception for input validation errors, you could define a class that inherits from the built-in ValueError class:

class ValidationError(ValueError):
    def __init__(self, message, field):
        self.message = message
        self.field = field

This custom exception class takes in a message and a field argument, which represent the error message and the field that caused the validation error, respectively. You could then raise this exception using the raise keyword, like this:

raise ValidationError("Invalid input", "email")

And catch it using a try-except block in the same way as before:

try:
    # code that might raise the exception goes here
except ValidationError as e:
    print(f"Error: {e.message} (field: {e.field})")

Custom exceptions can be useful for providing more informative error messages to the user, or for handling specific errors in a particular way in your code. By creating custom exception classes and raising them when necessary, you can add more flexibility and control to your error handling in Python.