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.

user-defined exceptions

The 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.
    CopiedCopy Code
    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:
    CopiedCopy Code
    try: 
       code 
    Except MyException as me: 
       print(me)
    
    

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

user-defined exception example

CopiedCopy Code

class MyException(Exception): 
   def __init__(self, arg): 
      self.msg = arg
def check(dict): 
      for k,v in dict.items(): 
         print('Name= {:15s} Balance= {:10.2f}'.format(k,v)) 
         if(v<2000.00): 
            raise MyException('Balance amount is less in the account of '+k) 
bank = {'Raj':5000.00, 'Vani':8900.50, 'Ajay':1990.00, 'Naresh':3000.00} 
try: 
  check(bank) 
except MyException as me: 
  print(me)