dantc12
dantc12

Reputation: 88

Python3 exception handling

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?

Upvotes: 0

Views: 875

Answers (2)

Veedrac
Veedrac

Reputation: 60137

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.

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122024

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))

Upvotes: 4

Related Questions