0

When running the following code:

try:
   key=int(input())
except ValueError as string:
   print("Error is within:",string)

for example, if one puts 'rrr' this exception will rise, since 'rrr' does not support (int)

However, instead ot putting the actual string, it puts: "invalid literal for int() with base 10: 'rrr' "

How do I make it work so that the variable 'string' actually gets the wrong input that the user gave (in this example, I want it to print: 'Error is within: rrr')

Thanks a lot

3
  • small hint: just post the complete error message Commented Jun 7, 2014 at 19:42
  • I can't do so, I have to post a given message that does not include the complete error message. Commented Jun 7, 2014 at 19:44
  • Pavel meant, post the exact traceback you are getting with your current code. Commented Jun 7, 2014 at 20:04

3 Answers 3

5

Store the input and convert it to an int separately.

key_str = input()
try:
    key = int(key_str)
except ValueError:
    print("Error is within:", key_str)
Sign up to request clarification or add additional context in comments.

Comments

5

Your issue comes from the fact that the variable string is the error message for a ValueError exception. If you wanted to print out the user's invalid input, you would need to create a variable that stores the user's input before your try/except. For example:

userInput = input()
try:
   key=int(userInput)
except ValueError:
   print("Error is within:",userInput)

2 Comments

can u redefine input?
@user3678068 Sure. input is just a name, so you can rebind it from the built-in function object to the string that function returns.
0

You can just parse the error msg :D

print("Error is within:", string.args[0][41:-1])

1 Comment

Exception.message was deprecated long ago, and removed from Python 3, which is what the OP is using.

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.