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 |
- Python Programming – Exception Handling
- Python Programming – Exception Handling
- Python Tutorial for Beginners | Learn Python Programming Basics
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: |
Output Enter a number: 7 Enter a number: 20 Enter a number: 4 Enter a number: 9 Enter a number: 11 Enter a number: 10 |