Updated April 1, 2023
Introduction to Python User Defined Exception
The following article provides an outline for Python User Defined Exception. Python user-defined exceptions can be written according to the customization and requirement of a particular programmer and which are not present internally in the pre-defined exceptions of python. While doing the coding and programming, it might happen that the code might go wrong at some or the other places.
In such a case, the python program throws an error or exception, which sometimes may result in the complete end of the program execution there itself. These situations can be handled by using the user defined exceptions and try-except statements. Using this, we can define what should be done exactly when a particular error or exception occurs or create new exceptions that we want to handle in our program.
Syntax of Python User Defined Exception
Some of the common predefined exceptions that mostly occur in python include FileNotFoundError, ImportError, TypeError, IOError, IndexError and ZeroDivisionError. Most of the exceptions end with the Error name in them. However, it is not a compulsion but a suggestion that whenever you will go for creating your own exception, you should name it so that it should end with Error word and have camel-case in it. The general way or syntax of creating a new user defined exception is to create a new class for the exception. This class should be directly or indirectly derived from the main Exception class.
The simple syntax of creating a new class in python is as shown below:
class yourUserDefinedExceptionError (Exception):
And further, you should specify the body of your exception, like what your program should exactly do when that exception occurs. Then, with the help of try-except statements used for exception and error handling, you can use your user defined exception.
How to Use Exceptions?
We can use the error handling mechanism like try and except provided in python to use the exceptions which we have defined and handle those errors or exceptions.
In order to get the complete detail or to get additional information about the Exception in python, you can execute the following command.
The execution of the above command gives the output similar to the image given below:
Examples of Python User Defined Exception
Given below are the examples of Python User Defined Exception:
Let us create a small exception by creating a new class for our user defined exception. It is necessary that out class should extend the base exception class. Our exception class name will be MyUserDefinedError, and we will use the ty except to check the working of our exception. The except statement will help to display the message containing the returned value from the exception.
# Sample example to demonstrate the working and creation of user defined exception in python # It is necessary that MyUserDefinedError class should be derived from the main super class of the Exception class MyUserDefinedError(Exception): # Initializer (Constructor) for the class def __init__(self, value): self.value = value # This will help to display the message of the exception def message(self): return(repr(self.value)) try: raise(MyUserDefinedError(9*8)) # returnedErrorMessage will store the value of the message or anything which will be returned by the exception except MyUserDefinedError as returnedErrorMessage: print ('The occurrence of the new exception is identified : ', returnedErrorMessage.value)
The execution of the above program gives the following output showing the calculated value of 9 * 8 returned from the exception class, which we defined.
Let us consider one more example of a user-defined exception. In this example, we will try to derive the error from the super class of Exception. This type of superclass exception is mostly used when we have a single module that should handle many different types of errors. We will try to do this by using this module to define the base class for our exceptions. Then, different subclasses will be created to define each exception class for distinct possible errors that need to be handled.
# Class which is derived from the main base class of Exception is DerivedClassError class class DerivedClassError(Exception): # Even though DerivedClassError is derived from the main base class of exceptions, # it will be used and considered as the base class for our user defined exception class pass class TransDerivedClassError(DerivedClassError): # This transition will occur when the transition will try to # perform the state which is actually not permitted to it def __init__(self, previous, next, message): self.previous = previous self.next = next # message will store the value generated from the error self.message = message try: raise(TransDerivedClassError(4,6*4,"Not Permitted")) # DerivedClassError will store the value of the user defined exception except TransDerivedClassError as DerivedClassError: print('There is an occurrence of exception: ',DerivedClassError.message)
The execution of the above program gives the following output showing the message “Not Permitted” returned from the exception class, which we defined.
We can even consider the standard predefined exceptions as the base class while creating our new user defined exception. Let us consider one of the examples of that type. RuntimeError is raised when the error which is occurred cannot be considered in any of the available categories of exceptions. RuntimeError is the in-built exception in python. Therefore, we can consider this class as the base class for our user-defined class instead of the main Exception class. The following program illustrates the usage of the same.
# SampleError is derived from the RuntimeError instead of main base class of Exception class SampleError(RuntimeError): def __init__(self, arg): self.args = arg try: raise SampleError("Exception") except SampleError as message: print (message.args)
The execution of the above program gives the following output and works in a similar way as it would have in case if we must have extended the main Exception class instead of RuntimeError class as the consideration of base class.
We can define exceptions according to the requirement and necessity in the program of python. There are many ways in which we can create these exceptions. They can be handled by a simple exception handling mechanism of try and except in python as the other predefined exceptions are handled.
This is a guide to Python User Defined Exceptions. Here we discuss the introduction, syntax, and how to use exceptions along with examples and code implementation. You may also have a look at the following articles to learn more –