User-defined Exceptions in Python
Generally, in Python errors and exceptions arises when the code goes wrong which intends leads to stop suddenly. But by exception handling method, we can handle some of the most frequent errors by using try-except statements. User can also create his/her own errors by defining an exception class. These exception classes have to be created or derived directly or indirectly from the exception class.
Deriving an Exception Class
Mostly names of the exception classes end with Error. We can define our own Exception Class in order to handle several distinct errors under a single module.
Python Code:
# NewError is a super class Exception
class NewError(Exception):
pass
class ValueError(NewError):
"""When Value does not satisfy condition"""
pass
Number = 5
while True:
try:
num=int(input('Enter the number: '))
if num < Number:
raise ValueError
if num > Number:
raise ValueError
break
except ValueError:
print("Value does not matched")
print("congratulations")
Output: