0

I'm trying to make a simple program (for learning purposes) using exception handling. What I'm trying to do is:

try:
    x = int(input())
except ValueError as var:
    # HERE I WANT TO USE THE 'x' STRING VALUE 

I know about the the various ways to use the exception message (for instance by using str(var)).

For example, if the input is bla which would cause a ValueError exception, print(var) outputs invalid literal for int() with base 10: 'bla', which is not really usable.

However, I created this program that should use str(var) to my advantage:

try:
    x = int(input())
except ValueError as var:
    s = str(var)
    print('Exception message: ' +s)
    i=0
    while (s[i] != '\''):
            i = i+1
        i = i+1
        print_str = ''
        while (s[i] != '\''):
            print_str = print_str + str(s[i])
            i++
        print('print_str = ' + print_str)

This program would probably work after a few changes..

So my question is: Is there a more direct way to get the 'x' string value?

3
  • 1
    Yes, i++ is invalid syntax. It has nothing to do with exception handling. Commented Jun 10, 2014 at 20:59
  • Python is not C++ nor Java. Commented Jun 10, 2014 at 20:59
  • Fixed it, my bad(probably because I use C++ more often). That lower program was not the main purpose of this question anyway.. Commented Jun 10, 2014 at 21:03

2 Answers 2

4

You can't access x in the except because it was never assigned - the exception is thrown somewhere in int(input(...)), before x = happens. Instead, do:

x = input(...)
try:
    x = int(x)
except ValueError:
    print("Couldn't make '{0}' an integer.".format(x))
Sign up to request clarification or add additional context in comments.

Comments

1

Furthering jonsharpe's response, you cannot catch most SyntaxErrors as they happen at compile time. Thus there's no hope whatsoever of even running the code, never mind recovering from the error.

Comments

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.