Introduction to Custom Exception in Python
Python has many built-in exceptions with it, apart from these built-in list python has the capability to provide custom exceptions to the users. These custom exceptions are named as user-defined exceptions. Here the user-defined exceptions can be built defined by using a class declared for it. These customer exceptions are declared specifically to satisfy user necessities. All the user-defined exceptions will be derived from the user 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 works?
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: Here two user-defined exceptions are used. One is used for checking whether the keyed in value is smaller than the check value, whereas the other user-defined exception is used for verifying whether the keyed in value is greater than the check value. So when an input value is keyed in by the user it is verified whether the user keyed in value is lesser than the check value, so when the exception is matched then To_small_value_exception is triggered. similarly when a keyed in value is greater than the check value then an exception stating To_large_value_exception is triggered. When both the exceptions are not triggered then the print statement stating ” keyed in value is acceptable!!. ” is printed onto 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: Here one user-defined exception is used. It is used to check whether the value given is falling between the range of zero to ten. So when an input value is keyed in by the user it is verified whether the user keyed in value falls between the given range of value, so when the exception is matched then Not_Suitable_value_exceptions is triggered. When no exception is triggered for the value then the statement ” The keyed in value is acceptable!!.” is printed onto 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: Here one user-defined exception is used. It is used to check whether the value given is a valid numeric or not. So when an input value is keyed in by the user it is verified whether the user keyed in value is of digit format, so when the exception is matched then Not_Suitable_value_exceptions is triggered. When no exception is triggered for the value then the statement ” The keyed in value is acceptable!!.” is printed onto 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:
Explanation: Here one user-defined exception is used. It is used to check whether the value given is a valid numeric or not. So when an input value is keyed in by the user it is verified whether the user keyed in value is a positive value or a negative value, This check is carried on by ensuring whether the keyed in value is less than zero, so when the exception is matched then Not_Suitable_value_exceptions is triggered. When no exception is triggered for the value then the statement ” The keyed in value is acceptable!!.” is printed onto the console.
Conclusion
Every programming language has the necessity of addressing special conditions. When conditions which have to be handled in a specific manner or when an exception has to be raised then the exception handling process comes into play in a vital way. The python’s exception handling setup is largely flexible and the custom exceptions is 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, working with examples. You can also go through our other related articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses