0

I'm practicing exception handling and when I try to execute the following code, python doesn't handle the TypeError exception if i enter a text instead of number. Following is the code :

num1=input("Enter the first number : ")
num2=input("Enter the second number : ")
try:
    num1=int(num1)
    num2=int(num2)
except TypeError:
    print("Sorry, that wasn't a number, please try again")
else:
    print(add)
1
  • It raises a ValueError, not a TypeError Commented Jun 9, 2016 at 8:24

1 Answer 1

1

This is because you are not tracking the correct error:

>>> int("not a number")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not a number'

ValueError is what you're looking for.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, now it worked. Why do we use TypeError then?
Quoting from docs.python.org/3/library/exceptions.html. TypeError - Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. Try typing '2' + 2 in python CLI.
@KushagraChughੴ: input() always returns a string, and int() takes a string object as argument. If you were to pass something in that was not a string (and not any of the other accepted types) you'd get a TypeError, e.g. int(None). But since you always pass in a string, that's not the case here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.