User defined exception if the user enters a string in input instead of a number
Here I am using class for a user-defined exception, I know that if I use ==> except Exception: it will work but i want to use user-defined exception ==> except error
class error(Exception):
pass
class b(error):
try:
age = int(input("Enter your age:\n>>"))
if(age >= 18):
print("You are Eligible for Voting")
elif(age < 18):
print("You are not Eligible for Voting")
else:
raise error
except error: # except Exception: --> it works
print("Invalid input")
print("Enter a number as your age")
obj = b()
output:-
Enter your age:
>> sdsd
Traceback (most recent call last):
File "c:\Users\HP\OneDrive\Desktop\All Desktop <br>apps\Python\Python_Programs\exception_handling.py", line 6, in <module>
class b(error):
File "c:\Users\HP\OneDrive\Desktop\All Desktop apps\Python\Python_Programs\exception_handling.py", line 8, in b
age = int(input("Enter your age:\n>>"))
ValueError: invalid literal for int() with base 10: 'sdsd'
class error(Exception):
pass
class b(error):
try:
try:
age = int(input("Enter your age:\n>>"))
except ValueError:
raise error
if age >= 18:
print("You are Eligible for Voting")
elif age < 18:
print("You are not Eligible for Voting")
except error: # except Exception: --> it works
print("Invalid input")
print("Enter a number as your age")
obj = b()
This will provide: