Userdefined Exceptions in Python with Examples (original) (raw)

User-defined Exceptions in Python with Examples

Last Updated : 04 Jan, 2025

In Python, exceptions are used to handle errors that occur during the execution of a program. While Python provides many built-in exceptions, sometimes we may need to create our own exceptions to handle specific situations that are unique to application. These are called user-defined exceptions.

To manage errors and exceptions, Python offers an exception handling mechanism using try and except blocks. Some common exceptions include IndexError, ImportError, IOError, ZeroDivisionError, TypeError and FileNotFoundError.

Creating User-Defined Exceptions

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