User defined exceptions in Python

219

Whenever an error or exception occurs in a python program, it itself throws standard expressions for those errors. But apart from these, we can also throw user defined expressions by customizing exception classes.

User defined exceptions in Python
User defined exceptions in Python

Customizing Exception Classes in Python

With the help of the code given below, we can get an overview of customizing exception classes in Python.

Code –

help(Exception)

Output –

Help on class Exception in module exceptions:

class Exception(BaseException)

 |  Common base class for all non-exit exceptions.

 |

 |  Method resolution order:

 |      Exception

 |      BaseException

 |      __builtin__.object

 |

 |  Methods defined here:

 |

 |  __init__(…)

 |      x.__init__(…) initializes x; see help(type(x)) for signature

 |

 |  ———————————————————————-

 |  Data and other attributes defined here:

 |

 |  __new__ = <built-in method __new__ of type object>

 |      T.__new__(S, …) -> a new object with type S, a subtype of T

 |

 |  ———————————————————————-

 |  Methods inherited from BaseException:

 |

 |  __delattr__(…)

 |      x.__delattr__(‘name’) <==> del x.name

 |

 |  __getattribute__(…)

 |      x.__getattribute__(‘name’) <==> x.name

 |

 |  __getitem__(…)

 |      x.__getitem__(y) <==> x[y]

 |

 |  __getslice__(…)

 |      x.__getslice__(i, j) <==> x[i:j]

 |

 |      Use of negative indices is not supported.

 |

 |  __reduce__(…)

 |

 |  __repr__(…)

 |      x.__repr__() <==> repr(x)

 |

 |  __setattr__(…)

 |      x.__setattr__(‘name’, value) <==> x.name = value

 |

 |  __setstate__(…)

 |

 |  __str__(…)

 |      x.__str__() <==> str(x)

 |

 |  __unicode__(…)

 |

 |  ———————————————————————-

 |  Data descriptors inherited from BaseException:

 |

 |  __dict__

 |

 |  args

 |

 |  message

Creating a user defined exception class in Python-

We can create our user-defined exception class but this needs to be derived from the built-in ones directly or indirectly.

Let’s will understand this with the help of the example given below –

class User_deferror(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return(repr(self.value))

try:
    raise(User_deferror("New User defined error"))

except User_deferror as error:
    print('A New Exception occurred:',error.value)

Output

A New Exception occurred: New User defined error

 

Creating a User-Defined Exception Class (Multiple Inheritance) –

When a single module handles multiple errors, then derived class exceptions are created. The base class is inherited by various user-defined classes to handle different types of errors.

Let’s understand this with the help of the example given below-

class User_def(Exception):

    """Base class for further exceptions"""
    pass

class Dividebyzero(User_def):

    """Raised when the input value is zero"""
    pass

try:

    i_num = int(input("Input your number: "))

    if i_num ==0:
        raise Dividebyzero

except Dividebyzero:

    print("Input value is zero,which will result an error")

print()

Output –

Enter a number: 
Input value is zero,which will result an error

Further, we can also create exceptions by using runtime error as a base class and user-defined error as a derived class.

Let’s understand this with the help of the example given below –

class Usererror(RuntimeError):

    def __init__(self, arg):

        self.args = arg

try:

    raise Usererror("userDefError")

except Usererror as e:

    print (e.args)

Output –

('u', 's', 'e', 'r', ‘D’, ‘e’, ‘f’, 'E', 'r', 'r', 'o', 'r')

In this article, we learned how can we create user-defined exceptions in python apart from the standard ones.

Attempt free Python Online Test

Python Exception Basics MCQ Test

Python Exception Coding MCQ Test

Previous articleException Handling in Python (Try, Except, Else, Finally)
Next articleOrderedDict In Python
Harshit brijwasi Yuvayana
I am Harshit Brijwasi. I am an engineer and a Technical Content writer. I am here to share my knowledge about technical topics and help researchers with them.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.