User Defined Exceptions in Python

When we write programs in python for real life applications, there are many constraints on the values which the variables can take in the program. For example, age cannot have a negative value. When a person inputs a negative value for age, the program should show an error message. But these types of constraints  cannot be applied in the python programs automatically. To handle these types of errors and force constraints on values, we use user defined exceptions in python. In this article we will look at different methods by which we can implement user defined exceptions in python.

What are user defined exceptions in python?

User defined exceptions in python are created by programmers to enforce constraints on the values which the variables in the program can take. Python has many built in exceptions which are raised when there is some error in the program. A program automatically terminates after showing which inbuilt exception has occurred while executing the program when it reaches into an undesired state. We can stop the program from entering into an undesired state by enforcing constraints using user defined exceptions.

User defined exceptions can be implemented by raising an exception explicitly, by using assert statement or by defining custom classes for user defined exceptions. We will study each method one by one in this article.

Using raise keyword explicitly after conditional statements

Inbuilt exceptions are raised automatically by a program in python but we can also raise inbuilt exceptions using the python try except blocks and raise keyword. By raising an inbuilt exception explicitly using raise keyword, we can use them anywhere in the program to enforce constraints on the values of variables.

For example, suppose we have to calculate the year of birth of a person from its age, we can do it as following:

age= 10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
10
Year of Birth is:
2011

The program has given proper output in the case by subtracting age from current year. Now suppose we give a negative value for age in input, say -10.

age= -10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Year of Birth is:
2031

When we provide a negative number for age, the program still works fine but gives an output which is logically incorrect because no person can have his year of birth in future.

To prevent this kind of year, we can check if the value given in age as input is negative and then we can force the program to raise an exception using raise keyword as follows.

The syntax for raise statement is raise ExceptionName . When an error is raised, the code in the except block should handle the exception otherwise it will cause error in the program.

try:
    age= -10
    print("Age is:")
    print(age)
    if age<0:
        raise ValueError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except ValueError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age.

Here we can see that for age -10, the program handles the case successfully. Lets check if it gives correct year of birth when given correct value of age.

try:
    age= 10
    print("Age is:")
    print(age)
    if age<0:
        raise ValueError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except ValueError:
    print("Input Correct age.")

Output:

Age is:
10
Year of Birth is:
2011

So, we can see that after using raise statement in try except block, the program gives correct output in both the cases. Now we will see how we can use assert statements to enforce the same constraint.

Using Assert statements to implement user defined exceptions in python

We can use assert statement to implement constraints on values of our variable in python. When, the condition given in assert statement is not met, the program gives AssertionError in output.

The syntax for assert statement in python is assert condition where condition can be any conditional statement which evaluates to True or False. When the condition in assert statement evaluates to True, the program works normally. When the condition in the assert statement evaluates to False, the program gives AssertionError.

To enforce the constraint that age should be greater than zero, we can use assert statement as shown in the following program.

age= 10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
10
Year of Birth is:
2011

When negative value is given as input for age, the condition will evaluate to false, and program will end due to AssertionError.

age= -10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Traceback (most recent call last):

  File "<ipython-input-9-214b1ab4dfa4>", line 4, in <module>
    assert age>0

AssertionError

We can also give a message to print when condition is not met in assert statement. The syntax for printing the message with assert statement is assert condition, message . message should be a string constant. Whenever the condition in assert statement evaluates to False, the program will raise an AssertionError and will print the message.

age= -10
print("Age is:")
print(age)
assert age>0 , "Age should be positive integer"
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Traceback (most recent call last):

  File "<ipython-input-10-82c11649bdd0>", line 4, in <module>
    assert age>0 , "Age should be positive integer"

AssertionError: Age should be positive integer

In the output, we can see that message that “Age should be positive integer” is also printed along with AssertionError.

We can also handle AssertionError by using try except block if want to disallow the program from exiting prematurely. There may be cases when python write to file operation has been performed, if the program exits prematurely, the data written in the file will not be saved. For the data written in the file to be saved, we need to close the file before the program exits. For this we will have to use try except blocks along with assert statement as follows.

try:
    age= -10
    print("Age is:")
    print(age)
    assert age>0
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except AssertionError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age.

In the output, we can see that when age is less than 0, AssertionError has occurred but it has been handled by code in except block. If we want to perform any file operation then we can implement the code in except block or we can use finally block to implement the code.

Defining custom classes for user defined exceptions

To create a user defined exception, we create a class with desired exception name which should inherit Exception class. After that, we can raise the exception in our code anywhere according to our need to implement constraints.

To generate a user defined exception, we use the “raise” keyword when a certain condition is met. The exception is then handled by the except block of the code. We then use pass statement. pass statement is used to show that we will not implement anything in our custom exception class. It is used as a placeholder and does nothing, still we have to use it because if we leave the body of our custom class empty, python interpreter will show that there is error in our code.

Example:

class NegativeAgeError(Exception):
    pass
try:
    age= -10
    print("Age is:")
    print(age)
    if age<0:
        raise NegativeAgeError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except NegativeAgeError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age.

Here we can see that when age has a value less than zero, the try block in the program throws NegativeAgeError using raise keyword. The exception is then handled by except block. If we will give correct value for age as input, it will print the year of birth normally.

class NegativeAgeError(Exception):
    pass
try:
    age= 10
    print("Age is:")
    print(age)
    if age<=0:
        raise NegativeAgeError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except NegativeAgeError:
    print("Input Correct age.")

Output:

Age is:
10
Year of Birth is:
2011

Conclusion:

In this article, we have seen how to implement constraints on values of variables in python using custom exception handling methods like assert keyword, raise keyword and custom exception class. We can also use user defined exceptions to implement different real life constraints in our program so that programs are syntactically correct and logically sound. Stay tuned for more articles.

Leave a Reply

Your email address will not be published. Required fields are marked *