Python Programming - Python User Defined Exceptions

Python Programming – Python User Defined Exceptions

In Python, users can create their own exceptions. This can be done by creating a new class that is derived from the Exception class. It is to be noted that most of the built-in exceptions are also derived from the Exception class. On the Python prompt, a user-defined exception can be created as follows as shown in Code 8.6. We see that a user-defined exception NewException is created which is derived from the Exception class. This exception can be raised just like other existing exceptions by using the raise statement with an optional error message.

Code: 8.6. Illustration of user defined exception NewException.

>>> class NewException(Exception):
… pass
…>>> raise NewException
Traceback (most recent call last):

__main__.NewException>>> raise NewException(“An error has occurred”)
Traceback (most recent call last):__main__,NewException:An error has occurred

An illustration of user-defined exceptions is given in Code: 8.7. This program presents a number game, where the user has to guess a number. If the user enters a number greater than the saved number then the message is displayed as the number is too large, otherwise, the message is displayed as the number is too small. This process continues until the user guesses the correct number. All this process is handled through user-defined exceptions. Here, a base class Guess is created derived from the built-in Exception class. Consequently, two derived classes, ValueTooSmall and ValueTooLarge are created, inherited from the Guess class.

Code: 8.7. Illustration of number game using user-defined exception.

# define Python user-defined exceptions
class Guess(Exception):
“””Base class for other exceptions”””
passclass ValueTooSmall(Guess):
“””Raised when the input value is too small”””
passclass ValueTooLarge(Guess):
“””Raised when the input value is too large”””
pass# our main program, where user guesses a number until he/she gets it right
# user needs to guess this number

number =10

while True:
try:
i_num = int(input(“Enter a number:”))
if i num< number:
raise ValueTooSmall
elifi_jium> number:
raise ValueTooLarge
break
except V alueT ooSmall:
print(“This value is too small, try again!”)
print()
except ValueTooLarge:
print(“This value is too large, try again!”)
print()
print(“Congratulations! You guessed it correctly.”)

Output

Enter a number: 7
This value is too small, try again!

Enter a number: 20
This value is too large, try again!

Enter a number: 4
This value is too small, try again!

Enter a number: 9
This value is too small, try again!

Enter a number: 11
This value is too large, try again!

Enter a number: 10
Congratulations! You guessed it correctly.

Python Tutorial

Leave a Reply

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