User Defined Exception

In this section we will learn about the user defined exceptions. In Python there are built in exceptions that makes the program to output an error whenever something goes wrong.

We can also define new exceptions according to our need by creating a new class. This class will have the user defined class and it will be derived from the Exception class either directly or indirectly.

Consider the following example:


>>> class UserDefinedError(Exception):


>>> raise UserDefinedError


Traceback (most recent call last):

  File “<pyshell#70>”, line 1, in <module>

    raise UserDefinedError



In the above example a class is made that is named as UserDefinedError and is derived from the class Exception. Then we used the raise keyword to raise this error.


Example: User defined Exception in Python

Consider the following example in which we have defined that how the user defined functions will raise and catch errors:


>>> class Error (Exception):


>>> class SmallValueError (Error):


>>> class LargeValueError (Error):


>>> n = 4

>>> while True:


                   num = int (input (“Enter a number:”))

                   if num < n:

                             raise SmallValueError

                   elif num > n:

                             raise LargeValueError


          except SmallValueError:

                   print (“You entered a small value”)

                   print ()

          except LargeValueError:

                   print (“You entered a large value”)

                   print ()


Enter a number:3

You entered a small value

Enter a number:5

You entered a large value

Enter a number:1

You entered a small value

Enter a number: 4


In the above example, the program is a guessing game in which the user has to guess the number, if the user enters a large number the exception is thrown to the LargeValueError exception and corresponding message is displayed.

If the user enters a small value then the exception is thrown to SmallValueError exception and the corresponding message is displayed. If the user enters the right number then the execution of the program stops.