0

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'


Shubham-Misal
  • 33
  • 1
  • 7

3 Answers3

0

When you input 'sdsd', you will get a ValueError from function int():

age = int(input("Enter your age:\n>>"))

so when you try to catch Error(that you defined), it doesn't work.

ValueError: invalid literal for int() with base 10: 'sdsd'

ValueError is a sub class of Exception, and when you catch Exception, your code can catch this ValueError, so it works.

0

The except clause only catches an exception if the exception is an instance of the exception class given to the except clause, or a subclass of it.

In your case, the int constructor raises ValueError when given a non-integer-formatted string as input, and since ValueError is a subclass of the Exception class, you can catch it with except Exception. But you cannot catch it with except error because the ValueError is not a subclass of your user-defined error class.

blhsing
  • 91,368
  • 6
  • 71
  • 106
0
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:

enter image description here

Thornily
  • 533
  • 3
  • 15