User Defined Exceptions in Python
To customize the exceptions, one has to write a class and inherit the Exception class which built-in one. One can give any name to the class any kind of statement can be given in it. Mostly these classes will have the init( ) function only where the error message is initialized. Any number of arguments can be passed to this user defined exception class.
Let us look at examples to understand it deeper.
Here we have defined a class error to handle the exception caused by user input. It has a variable called msg to hold the error message.
Now outside the class in the try block we have written the code to get user input with a condition that the input must be less than 15 and greater than 5. If the input does not satisfy this criteria, then exception will be raised.
The except block contains the name of the class. You can define another name
for the same class for easy access using
as keyword or even skip it and write the whole
class name as it is. Now we can print the message stored in the variable to
display the error.
The arguments can be passes as we desire. Now depending on the constraints we can customize the message to be displayed. Look at the code below.
Here we pass an argument 'm' to the
constructor of the class which sets the error message. By this method, we can
define any number of constraints with a single class.
You can even create separate class for handling different exceptions.
Consider the example above. It can be modified as given below.
Comments
Post a Comment