Python User-Defined Exceptions
Overview
Python has many built-in exceptions which force the program to raise an error when something goes wrong. However, sometimes, we may need to create custom exceptions that serve our purpose.
Python User-Defined Exceptions
In Python, users can define custom exceptions by creating a new class. This exception class must be derived directly or indirectly from the Exception class, which is the source of most built-in exceptions.
Example
Let’s understand the concept with an example. In this example, we will illustrate how user-defined exceptions can be used in a program to raise and catch errors. This program will prompt the user to enter a number until they guess a stored number correctly. To help them figure it out, a hint is provided as to whether their guess is greater than or less than the secret.
Python Program
###########
# Python program User defined Exception
# Python Tutorials - www.TestingDocs.com
###########
class GuessSmallError(Exception):
“Exception raised when guess is small”
pass
class GuessLargeError(Exception):
“Exception raised when guess is large”
pass
# Secret number .. ssshhhh!!!
secret = 21
# Python while loop
while True:
#Python try-except code block
try:
guess= int(input(“Enter guess number:”))
if(guess < secret): raise GuessSmallError elif(guess > secret):
raise GuessLargeError
else:
break
except GuessSmallError:
print(“Your guess is small, Try Again…”)
except GuessLargeError:
print(“Your guess is large, Try Again…”)
print(“Congratulations! Your guess is correct.”)
Sample Program Run Output
= RESTART: C:/PythonPrograms/user_defined.py
Enter guess number:45
Your guess is large, Try Again…
Enter guess number:3
Your guess is small, Try Again…
Enter guess number:10
Your guess is small, Try Again…
Enter guess number:17
Your guess is small, Try Again…
Enter guess number:22
Your guess is large, Try Again…
Enter guess number:19
Your guess is small, Try Again…
Enter guess number:20
Your guess is small, Try Again…
Enter guess number:21
Congratulations! Your guess is correct.
—
Python Tutorials
Python Tutorial on this website can be found at:
More information on Python is available at the official website: