User-Defined Errors In Python

This post provides a way of generating or raising and error based on the user’s conditions in contrast to the common errors raised by the compiler/interpreter. We call such errors as user-defined errors or exceptions in Python.

Prerequisites: Error handling in Python (refer to this). Basics of classes and inheritance in Python (refer to this)

User-Defined Errors

As the name suggests, user-defined errors are exceptions that the programmer can raise an exception based on his own condition. This is useful on several occasions, but more on that towards the end of the post.

In order to raise an user-defined exception, one must first define an exceptions class as a derived class of the built-in “Exception” class. After that, each type of error can be defined as an object instance of that class. The object can be given an argument which will serve as the error message when the error is raised and can be printed if necessary.

As and when required, we can use the “raise” keyword followed by the error object name, to raise an exception. When the execution raises this error, we can handle it like any other error (like ValueError, IndexError, etc.)

Implementing User-Defined Errors in Python

Consider the following program,

class myErrors(Exception):
    pass

NumError = myErrors("No Numbers Allowed")
AlphaError = myErrors("No Alphabets Allowed")

inp = raw_input("Enter string without numbers and letters: ")
try: 
    for k in inp:
        if k.isdigit():
            raise NumError
        elif k.isalpha():
            raise AlphaError
except myErrors as m:
    print m.message
else:
    print "String Entered is Valid"

    

The above program accepts user input.

It checks for if it contains numbers or letters and raises suitable exceptions using the concerned “object” name. However, the exception statement can have either the object names to catch the specific errors or can contain the Exception class or its derived classes. In this case, we have used “myErrors” class. It will catch any error that any of its objects raises.

Notice the “as” keyword followed by a variable. it stores all attributes of the caught error object. In this case, we use the variable to display the error message defined for that particular exception. If execution raises NumError, then it prints the corresponding message and similarly for AlphaError.

The following is the output for the above program,

User-Defined Errors In Python

If we want to catch only one of the exceptions or want to handle each error differently, we can simply use “except NumError” or otherwise. This will execute the except block only if NumError was raised. If AlphaError was raised and since there is no suitable except statement, the interpreter will report the error and terminate the program.

The following program illustrates this,

class myErrors(Exception):
    pass

NumError = myErrors("No Numbers Allowed")
AlphaError = myErrors("No Alphabets Allowed")

inp = raw_input("Enter string without numbers and letters: ")
try: 
    for k in inp:
        if k.isdigit():
            raise NumError
        elif k.isalpha():
            raise AlphaError
except NumError as m:
    print m.message
else:
    print "String Entered is Valid"

    

Notice the output. For this input, the execution raises the AlphaError. Since there is no except statement for AlphaError, the interpreter displays an error message and terminates the program run,

errors in Python

The usefulness of User-Defined Errors

The ability to raise user-defined exceptions is particularly useful in large projects. Instead of printing an error message repeatedly, the error can be raised. An except statement can be provided for a large chunk of code, thereby finding any errors occurring.

Moreover, in case you are inside 3 levels of looping construct (say) and you wish to come out of all of them and do something else when a particular situation occurs. One would have to use flag variables and break out of three loops. Instead, if an exception is raised, it directly jumps down to the except statement, which can be strategically placed to handle and exception. Apart from these, user-defined exceptions are useful in a variety of ways.

 

Feel free to leave behind any sort of feedback, suggestions, doubts below.

Leave a Reply

Your email address will not be published.