In Python user-defined exceptions ,users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class.
CREATING A USER-DEFINED EXCEPTION CLASS
Here we created a new exception class i.e. User_Error. Exceptions need to be derived from the built-in Exception class, either directly or indirectly. Let’s look at the given example which contains a constructor and display method within the given class.
#class MyError is extented from super class Exception
class User_Error(Exception):
# constructor method
def __init__(self,value):
self.value = value
# __str__display function
def __str__(self):
return(repr(self.value))
try:
raise(User_Error("User defined error"))
# Value of Exception is stored in error
except User_Error as error:
print('A New Exception occured:',error.value)
CREATING A USER-DEFINED EXCEPTION CLASS (USING MULTIPLE INHERITENCE)
Derived class Exceptions are created when a single module handles multiple several distinct errors. Here we created a base class for exceptions defined by that module. This base class is inherited by various user-defined class to handle different types of errors.
# define python user-defined exceptions
class Error(Exception):
"""Base clase for other exceptions"""
pass
class Dividebyzero(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num ==0:
raise Dividebyzero
except Dividebyzero:
print("Input value is zero, try again!")
print()
Creating a User-defined Exception class (standard Exceptions)
Runtime error is a built-in class which is raised whenever a generated error does not fall into mentioned categories. The program below explains how to use runtime error as base class and user-defined error as derived class.
# User defined error
class Usererror(RuntimeError):
def __init__(self,arg):
self.args = arg
try:
raise Usererror("usererror")
except Usererror as e:
print (e.args)
Top comments (0)