Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is User-Defined Exceptions in Python?
3.
Creating User-defined Exceptions
3.1.
Python
4.
The Exception Class
5.
Raising User-defined Exception
6.
Catching Exception
7.
Deriving Error from Super Class Exception
7.1.
Python
8.
Using Standard Exceptions as a Base Class
8.1.
Python
9.
Frequently Asked Question
9.1.
What is a user-defined exception in Python?
9.2.
What are the types of exceptions in Python?
9.3.
How do you create a user-defined exception?
9.4.
Which keyword is used to throw a user-defined exception?
10.
Conclusion
Last Updated: Jun 2, 2024
Easy

User-defined Exception in Python

Author Sanjana Yadav
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

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 User-Defined Exceptions 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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating User-defined Exceptions

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)

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)

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)

Output

('N', 'e', 't', 'w', 'o', 'r', 'k', 'E', 'r', 'r', 'o', 'r')

Frequently Asked Question

What is a user-defined exception in Python?

Programmers generate user-defined exceptions in Python to impose limits on the values that variables in the program can take. Python contains several built-in exceptions that are thrown when the program encounters an error.

What are the types of exceptions in Python?

Python has two main exception types:

  1. Built-in exceptions: These handle common errors like ZeroDivisionError (division by zero) or NameError (undefined variable).
  2. User-defined exceptions: You create these to handle specific errors in your code, providing more informative messages.

How do you create a user-defined exception?

When creating your own exceptions, use the term "Exception" at the end of the class name and implement the three typical constructors, as shown in the example below. EmployeeListNotFoundException is a new exception class defined in the example.

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

Previous article
Catching an Exception in Python (try-except)
Next article
Built-in Exception in Python
Live masterclass