Python - User-Defined Exceptions



Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.

Here is an example that has a user-defined MyException class. Here, a class is created that is subclassed from base Exception class. This is useful when you need to display more specific information when an exception is caught.

In the try block, the user-defined exception is raised whenever value of num variable is less than 0 or more than 100 and caught in the except block. The variable e is used to create an instance of the class MyException.

Example

class MyException(Exception):
   "Invalid marks"
   pass
   
num = 10
try:
   if num <0 or num>100:
      raise MyException
except MyException as e:
   print ("Invalid marks:", num)
else:
   print ("Marks obtained:", num)

Output

For different values of num, the program shows the following output

Marks obtained: 10
Invalid marks: 104
Invalid marks: -10
Advertisements