Introduction to Custom Exception in Python
Python has many built-in exceptions with it; apart from these built-in lists, python has the capability to provide custom exceptions to the users. User-defined exceptions are indeed named as such because they are created and defined by users to meet specific requirements. These exceptions can be constructed by declaring a class for them. User-defined exceptions are designed to cater to specific needs and can be derived from a user-defined class.
Syntax
class User_Exception1( Exception ) ....class User_Exception2( Exception ) .... . . . . . . try:Executed on top of suspicious code except User_Exception1: This piece will be executed when a user_exception 1 is triggeredexcept User_Exception2: This piece will be executed when a user_exception 1 is triggered else: This block is executed when no orther exception is found
How User-defined Exception Handling work?
A user-defined exception-handling process needs to have a user-defined class representing the exception to be created. This user-defined exception class needs to be inheriting the exception class either directly or indirectly. So based on the inherited class, this formulates into a user-based exception.
Examples to Implement Custom Exception in Python
Below are some examples:
Example #1
Code:
# The user defined exceptions are declared here
class Error(Exception):
"""Base class for other exceptions"""
pass
class To_small_value_exception(Error):
"""This exception will be raised when the keyed in value is too small"""
pass
class To_large_value_exception(Error):
""" This exception will be raised when the keyed in value is too large"""
pass
Check_value = 10
while True:
try:
Input_Number = int(input("Enter a number: "))
if Input_Number < Check_value:
raise To_small_value_exception
elif Input_Number > Check_value:
raise To_large_value_exception
break
except To_small_value_exception:
print("The keyed in value is very small")
print()
except To_large_value_exception:
print("The keyed in value is very large")
print()
print("The keyed in value is acceptable!!.")
Output:
Explanation: In this scenario, two user-defined exceptions are utilized. One is used to check if the entered value is smaller than a specified check value, while the other exception is employed to verify if the entered value is greater than the check value. When a user provides an input value, it is validated to determine if it is smaller than the check value. If the condition is met, the “To_small_value_exception” exception is triggered. Similarly, if the input value is greater than the check value, the “To_large_value_exception” exception is raised. When neither of these exceptions is triggered, the statement “Keyed-in value is acceptable!!” is printed on the console.
Example #2
Code:
# The user defined exceptions are declared here
class Error(Exception):
""" Base class for other exceptions """
pass
class Not_Suitable_value_exception(Error):
""" This exception will be raised when the keyed in value is not in range """
pass
while True:
try:
Input_Number = int(input("Enter a number: "))
if Input_Number not in range(1,10):
raise Not_Suitable_value_exception
break
except Not_Suitable_value_exception:
print("The keyed in value is not suitable")
print()
print("The keyed in value is acceptable!!.")
Output:
Explanation: In this scenario, a user-defined exception is utilized to validate whether a given value falls within the range of zero to ten. When a user enters a value, it is checked to verify if it falls within the specified range. If the value does not meet the criteria, the exception “Not_Suitable_value_exceptions” is triggered. However, if the value falls within the specified range and does not trigger an exception, the statement “The keyed-in value is acceptable!!” is printed on the console.
Example #3
Code:
# The user defined exceptions are declared here
class Error(Exception):
""" Base class for other exceptions """
pass
class Not_Suitable_value_exception(Error):
""" This exception will be raised when the keyed in value is not integer """
pass
while True:
try:
Input_Number = input("Enter a number: ")
if not Input_Number.isdigit():
raise Not_Suitable_value_exception
break
except Not_Suitable_value_exception:
print("The keyed in value is not suitable")
print()
print("The keyed in value is acceptable!!.")
Output:
Explanation: In this scenario, a user-defined exception is used to validate the input value’s numeric format. When a user provides a value, it undergoes a check to ensure it is in a valid digit format. If the value does not meet the required criteria, the “Not_Suitable_value_exceptions” exception is raised. However, if the value passes the validation without triggering an exception, the statement “The keyed-in value is acceptable!!” is printed on the console.
Example #4
Code:
# The user defined exceptions are declared here
class Error(Exception):
""" Base class for other exceptions """
pass
class Not_Suitable_value_exception(Error):
""" This exception will be raised when the keyed in value is not positive """
pass
while True:
try:
Input_Number = int(input("Enter a number: "))
if Input_Number <= 0:
raise Not_Suitable_value_exception
break
except Not_Suitable_value_exception:
print("The keyed in value is not positive")
print()
print("The keyed in value is positive!!.")
Output:
Conclusion
Every programming language has the necessity of addressing special conditions. The exception-handling process becomes crucial when specific conditions need to be handled in a particular manner or when it is necessary to raise an exception. Python’s exception handling setup is largely flexible, and custom exceptions are among the primary capability of Python exception handling setup. The above-discussed examples precisely exhibit how custom exceptions are handled in python programming.
Recommended Articles
This is a guide to Custom Exception in Python. Here we discuss an introduction to Custom Exception in Python, syntax, and working with examples. You can also go through our other related articles to learn more –