Table of contents
1.
What is a User-defined Exception in Python?
2.
How to Create User-defined Exception?
2.1.
Python
3.
The Exception Class
4.
Raising User-defined Exception
5.
Catching Exception
6.
Deriving Error from Super Class Exception
6.1.
Python
7.
Using Standard Exceptions as a Base Class
7.1.
Python
8.
Example of Creating User-Defined Exception in Python
8.1.
Example 1: Basic User-Defined Exception
8.2.
Python
8.3.
Example 2: User-Defined Exception with Custom Attributes
8.4.
Python
8.5.
Example 3: User-Defined Exception with Inheritance
8.6.
Python
8.7.
Example 4: Chained User-Defined Exceptions
8.8.
Python
9.
Frequently Asked Question
9.1.
Why would I need to create a user-defined exception in Python?
9.2.
Can user-defined exceptions inherit from built-in exceptions in Python?
9.3.
Can I define multiple user-defined exceptions in a single Python program?
9.4.
Which keyword is used to throw a user-defined exception?
10.
Conclusion
Last Updated: Aug 27, 2024
Easy

User-defined Exception in Python with Examples

Author Sanjana Yadav
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

When code goes wrong in Python, it throws errors and exceptions, which can cause the program to crash. With the assistance of try-except, Python additionally provides an exception handling approach. IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError are just a few of the most common errors. Using the exception class, a user may construct his own error.

User-defined exception in python

Also Read, Floor Division in Python and Convert String to List Python.

What is a User-defined Exception in Python?

User-defined exceptions in Python are custom error messages you create to handle specific errors in your code. They inherit from the built-in Exception class. This lets you provide more informative error messages than generic ones like ValueError.

For example, you can define an InvalidAgeException to catch attempts to enter an age below 18. This makes your code clearer and easier to debug.

How to Create User-defined Exception?

By creating a new exception class, programmers may name their own exceptions. Exceptions must be either directly or indirectly inherited from the Exception class. Although it is not required, most exceptions are given names that end in "Error," similar to how standard Python exceptions are titled. 

Consider the following example:

  • Python

Python

class SampleError(Exception):
   # Constructor
   def __init__(self, val):
       self.val = val


   # __str__ to print() the value
   def __str__(self):
       return(repr(self.val))



try:
   raise(SampleError(5*6))
  
# Value of Exception stored in error
except SampleError as error:
   print('A new Exception occurred: ', error.val)
You can also try this code with Online Python Compiler
Run Code

Output

A new Exception occurred:  30

Must Read, python packages

The Exception Class

Run the code below to understand more about the class Exception.

help(Exception)
class Exception(BaseException)
 |  Common base class for all non-exit exceptions.
 |  
 |  Method resolution order:
 |      Exception
 |      BaseException
 |      object
 |  
 |  Built-in subclasses:
 |      ArithmeticError
 |      AssertionError
 |      AttributeError
 |      BufferError
 |      ... and 15 other subclasses
 |  
 |  Methods defined here:
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  ----------------------------------------------------------------------

 

You can also read about the Multilevel Inheritance in Python, Fibonacci Series in Python.

Raising User-defined Exception

1. Create a Custom Exception Class:

We inherit from the built-in Exception class to create our own exception type. Here, we define InvalidAgeException:

class InvalidAgeException(Exception):
    def __init__(self, message):
        super().__init__(message)  # Call parent constructor with message

2. Raise the Exception with raise:

Use the raise keyword followed by the exception instance to signal an error condition. Optionally, you can provide a custom message:

def check_age(age):
    if age < 18:
        raise InvalidAgeException("You must be at least 18 years old.")

Output (if check_age(17) is called):

Traceback (most recent call last):
  File "<ipython-input-1-i5JKj9vleaNI>", line 5, in check_age
    raise InvalidAgeException("You must be at least 18 years old.")
InvalidAgeException: You must be at least 18 years old.

Catching Exception

1. Use try...except Block:

The try block contains code that might raise an exception. The except block handles the exception if it occurs:

try:
    check_age(17)
except InvalidAgeException as e:
    print(e)  # Print the error message

Output (if check_age(17) is called):

InvalidAgeException: You must be at least 18 years old.

2. Specific vs. General Exceptions:

  • It's better to catch the specific exception type (InvalidAgeException here) for tailored handling.
  • Use except Exception as a last resort to catch any exception, but it can mask other issues.

Deriving Error from Super Class Exception

When a module has to handle many errors, superclass Exceptions are created. Creating a base class for exceptions specified by that module is a standard technique to accomplish this. Particular subclasses are also created in order to construct customized exception classes for various error scenarios.

  • Python

Python

class SampleError(Exception):
   pass



class TransitionError(SampleError):
   def __init__(self, prev, next, message):
       self.prev = prev
       self.next = next
       self.message = message



try:
   raise(TransitionError(4, 4*2, "Not Allowed"))
except TransitionError as error:
   print('An Exception occurred: ', error.message)
You can also try this code with Online Python Compiler
Run Code

Output

An exception occurred:  Not Allowed

Using Standard Exceptions as a Base Class

A runtime error is a type of exception that is thrown when a created error does not fit into any of the categories. This program demonstrates how to utilize network error as a derived class and runtime error as a base class. An exception can be derived in the same way from Python's standard exceptions.

  • Python

Python

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


try:
   raise NetworkError("NetworkError")


except NetworkError as error:
   print (error.args)
You can also try this code with Online Python Compiler
Run Code

Output

('N', 'e', 't', 'w', 'o', 'r', 'k', 'E', 'r', 'r', 'o', 'r')
You can also try this code with Online Python Compiler
Run Code

Example of Creating User-Defined Exception in Python

Example 1: Basic User-Defined Exception

  • Python

Python

class NegativeValueError(Exception):
def __init__(self, value):
self.value = value
super().__init__(f"Negative value error: {value}")

def square_root(x):
if x < 0:
raise NegativeValueError(x)
return x ** 0.5

try:
print(square_root(-4))
except NegativeValueError as e:
print(e)
You can also try this code with Online Python Compiler
Run Code

Output:

Negative value error: -4

Explanation: In this example, a user-defined exception NegativeValueError is created to handle cases where a negative value is passed to a function that calculates the square root. The __init__ method of the exception class is used to customize the error message. When square_root(-4) is called, the exception is raised, and the custom error message is printed.

Example 2: User-Defined Exception with Custom Attributes

  • Python

Python

class AgeRestrictionError(Exception):
def __init__(self, age, message="Age must be 18 or older."):
self.age = age
self.message = message
super().__init__(self.message)

def enter_club(age):
if age < 18:
raise AgeRestrictionError(age)
return "Access granted."

try:
print(enter_club(16))
except AgeRestrictionError as e:
print(f"Access denied: {e.message} (Age provided: {e.age})")
You can also try this code with Online Python Compiler
Run Code

Output:

Access denied: Age must be 18 or older. (Age provided: 16)

Explanation: This example defines an AgeRestrictionError exception that takes both an age and an optional message. The enter_club function raises this exception if the age is less than 18. The custom attributes age and message allow for a detailed error response when the exception is caught.

Example 3: User-Defined Exception with Inheritance

  • Python

Python

class InvalidInputError(ValueError):
def __init__(self, input_value, message="Invalid input provided."):
self.input_value = input_value
self.message = message
super().__init__(self.message)

def check_even_number(number):
if number % 2 != 0:
raise InvalidInputError(number)
return f"{number} is an even number."

try:
print(check_even_number(7))
except InvalidInputError as e:
print(f"Error: {e.message} (Input: {e.input_value})")
You can also try this code with Online Python Compiler
Run Code

Output:

Error: Invalid input provided. (Input: 7)

Explanation: Here, InvalidInputError is a user-defined exception that inherits from Python's built-in ValueError class. The check_even_number function raises this exception if the input number is not even. The inheritance from ValueError allows InvalidInputError to be used in contexts where ValueError is expected.

Example 4: Chained User-Defined Exceptions

  • Python

Python

class DivisionByZeroError(Exception):
pass

class InvalidOperandError(Exception):
pass

def divide(a, b):
if b == 0:
raise DivisionByZeroError("Cannot divide by zero.")
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise InvalidOperandError("Operands must be numeric.")
return a / b

try:
result = divide(10, 0)
except DivisionByZeroError as e:
print(f"Division error: {e}")
except InvalidOperandError as e:
print(f"Operand error: {e}")
You can also try this code with Online Python Compiler
Run Code

Output:

Division error: Cannot divide by zero.

Explanation: In this example, two user-defined exceptions, DivisionByZeroError and InvalidOperandError, are defined to handle different error cases in a division operation. The divide function checks for both division by zero and invalid operand types, raising the appropriate exception. The code demonstrates handling multiple custom exceptions using try-except blocks.

Frequently Asked Question

Why would I need to create a user-defined exception in Python?

Creating user-defined exceptions allows you to handle specific error conditions that are unique to your application, making your code more robust and easier to debug by providing meaningful error messages.

Can user-defined exceptions inherit from built-in exceptions in Python?

Yes, user-defined exceptions can inherit from built-in exceptions in Python. This allows them to be used in contexts where built-in exceptions are expected and to take advantage of built-in exception behavior.

Can I define multiple user-defined exceptions in a single Python program?

Yes, you can define multiple user-defined exceptions in a single Python program. This is useful for handling different error scenarios separately, allowing for more granular error handling and clearer, more maintainable code.

Which keyword is used to throw a user-defined exception?

The throw keyword is used by the user to throw an exception. This exception is handled using IO Exception. A custom exception class must be present in the user-defined exception.

Conclusion

In this article, we have extensively discussed the User-defined exception in the python class. We learned to create a user-defined exception in Python. We also learned about exception classes and how to use standard exceptions as a base class.

We hope that this blog has helped you enhance your knowledge of the user-defined exception in Python and if you would like to learn more about exception handling in Python, check out our articles on exception handling in python

Live masterclass