We create user-defined or custom exceptions by creating a new exception class in Python. The idea is to derive the custom exception class from the exception class. Most built-in exceptions use the same idea to enforce their exceptions.
In the given code, you have created a user-defined exception class, the “CustomException“. It is using the Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does i.e. by calling the “raise” statement with an optional error message.
Let’s take an example.
In this example, we show how to raise a user-defined exception and catch errors in a program. Also, in the sample code, we ask the user to enter an alphabet again and again until he enters the stored alphabet only.
For help, the program provides a hint to the user so that he can figure out the correct alphabet.
#Python user-defined exceptions class CustomException(Exception): """Base class for other exceptions""" pass class PrecedingLetterError(CustomException): """Raised when the entered alphabet is smaller than the actual one""" pass class SucceedingLetterError(CustomException): """Raised when the entered alphabet is larger than the actual one""" pass # we need to guess this alphabet till we get it right alphabet = 'k' while True: try: foo = raw_input ( "Enter an alphabet: " ) if foo < alphabet: raise PrecedingLetterError elif foo > alphabet: raise SucceedingLetterError break except PrecedingLetterError: print("The entered alphabet is preceding one, try again!") print('') except SucceedingLetterError: print("The entered alphabet is succeeding one, try again!") print('') print("Congratulations! You guessed it correctly.")