(python) User-defined exception not working, using class { don't know why the exception is not working when i enter a string }

Question:

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:UsersHPOneDriveDesktopAll Desktop <br>appsPythonPython_Programsexception_handling.py", line 6, in <module>
    class b(error):
  File "c:UsersHPOneDriveDesktopAll Desktop appsPythonPython_Programsexception_handling.py", line 8, in b
    age = int(input("Enter your age:n>>"))
ValueError: invalid literal for int() with base 10: 'sdsd'


Asked By: Shubham-Misal

||

Answers:

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.

Answered By: Eric CHEUNG

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.

Answered By: blhsing
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

Answered By: Thornily
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.