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.


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


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

Marks obtained: 10
Invalid marks: 104
Invalid marks: -10
Kickstart Your Career

Get certified by completing the course

Get Started