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:

CODE

>>> class UserDefinedError(Exception):

          pass

>>> raise UserDefinedError

OUTPUT

Traceback (most recent call last):

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

    raise UserDefinedError

UserDefinedError

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:

CODE

>>> class Error (Exception):

          pass

>>> class SmallValueError (Error):

          pass

>>> class LargeValueError (Error):

          pass

>>> n = 4

>>> while True:

          try:

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

                   if num < n:

                             raise SmallValueError

                   elif num > n:

                             raise LargeValueError

                   break

          except SmallValueError:

                   print (“You entered a small value”)

                   print ()

          except LargeValueError:

                   print (“You entered a large value”)

                   print ()

OUTPUT

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

enter-a-number

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.