A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/user-defined-exceptions-python-examples/ below:

User-defined Exceptions in Python with Examples

User-defined Exceptions in Python with Examples

Last Updated : 22 Jul, 2025

User-defined exceptions are created by defining a new class that inherits from Python's built-in Exception class or one of its subclasses. By doing this, we can create custom error messages and handle specific errors in a way that makes sense for our application.

Steps to Create and Use User-Defined Exceptions

Example of a User-Defined Exception:

Python
# Step 1: Define a custom exception class
class InvalidAgeError(Exception):
    def __init__(self, age, msg="Age must be between 0 and 120"):
        self.age = age
        self.msg = msg
        super().__init__(self.msg)

    def __str__(self):
        return f'{self.age} -> {self.msg}'

# Step 2: Use the custom exception in your code
def set_age(age):
    if age < 0 or age > 120:
        raise InvalidAgeError(age)
    else:
        print(f"Age set to: {age}")

# Step 3: Handling the custom exception
try:
    set_age(150)  # This will raise the custom exception
except InvalidAgeError as e:
    print(e)

Output
150 -> Age must be between 0 and 120

Explanation:

Customizing Exception Classes

When we create a custom exception, we subclass Python’s built-in Exception class (or a subclass like ValueError, TypeError, etc.). We can then add our own attributes, methods or custom logic to make our exception more informative.

Python
# Step 1: Subclass the Exception class

class InvalidAgeError(Exception):
    def __init__(self, age, msg="Age must be between 0 and 120", error_code=1001):
        # Custom attributes
        self.age = age
        self.msg = msg
        self.error_code = error_code
        super().__init__(self.msg)  # Call the base class constructor

    # Step 2: Customize the string representation of the exception
    
    def __str__(self):
        return f"[Error Code {self.error_code}] {self.age} -> {self.msg}"

# Step 3: Raising the custom exception

def set_age(age):
    if age < 0 or age > 120:
        raise InvalidAgeError(age)
    else:
        print(f"Age set to: {age}")

# Step 4: Handling the custom exception with additional information

try:
    set_age(150)  # This will raise the custom exception
except InvalidAgeError as e:
    print(e)

Output
[Error Code 1001] 150 -> Age must be between 0 and 120

Explanation:

How to use standard Exceptions as a base class?

A runtime error is a class that is a standard exception that is raised when a generated error does not fall into any category. This program illustrates how to use runtime error as a base class and network error as a derived class. In a similar way, an exception can be derived from the standard exceptions of Python.

Python
# NetworkError has base RuntimeError and not Exception
class Networkerror(RuntimeError):
    def __init__(self, arg):
        self.args = arg

try:
    raise Networkerror("Error")

except Networkerror as e:
    print(e.args)

Output

('E', 'r', 'r', 'o', 'r')


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4