Python User Defined Exceptions

Like the built-in exceptions of Python, the programmer can also create his own exceptions which are called 'User- defined exceptions' or 'Custom exceptions'.We know Python offers many exceptions which will raise in different contexts. For example, when a number is divided by zero, the ZeroDivisionError is raised. Similarly, when the datatype is not correct, TypeError is raised.


Steps to be followed for User Defined Exceptions
  1. Since all exceptions are classes, the programmer is supposed to create his own exception as a class. Also, he should make his class as a sub class to the in-built 'Exception' class.
    class MyException(Exception): 
    def __init__(self, arg): 
    self.msg = arg

    Here, 'MyException' class is the sub class for 'Exception' class.This class has a constructor where a variable 'msg' is defined.This 'msg' receives a message passed from outside through 'arg'.

  2. The programmer can write his code; maybe it represents a group of statements or a function. When the programmer suspects the possibility of exception, he should raise his own exception using 'raise' statement as: raise MyException('message')

    Here, raise statement is raising MyException class object that contains the given 'message'.

  3. The programmer can insert the code inside a 'try' block and catch the exception using 'except' block as:
    try: 
       code 
    Except MyException as me: 
       print(me)

    Here, the object 'me' contains the message given in the raise statement.

A Python program to create our own exception and raise it when needed.