Try: Except: not catching ValueError (Help)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Eclipse
    New Member
    • Dec 2007
    • 6

    Try: Except: not catching ValueError (Help)

    G'day all

    In the code below I am trying to catch an error thrown if i enter any other value than an integer. (I used the string 'six' and the float '1.5')

    The error thrown in the command window by the code is:

    Traceback (most recent call last):
    File "C:\Documen ts and Settings\Smythv ille\My Documents\Pytho n\Stuff\Ch4\ex1-6.py", line 59, in <module>
    a = int(raw_input(" \nTry a number!"))
    ValueError: invalid literal for int() with base 10: 'six'

    [CODE=python]
    a = int(raw_input(" \nTry a number!"))

    try:
    if a >= 0 and a <= 9:
    print "\nYour number is between or equal to 0 and 9."
    else:
    print "\nYour number is not between or equal to 0 and 9."
    except ValueError:
    print "Could not convert data to an integer."
    [/CODE]
    Even though I have specified the ValueError is doesn't catch it.

    Any Ideas?

    Thanks

    Eclipse
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by Eclipse
    G'day all

    In the code below I am trying to catch an error thrown if i enter any other value than an integer. (I used the string 'six' and the float '1.5')

    The error thrown in the command window by the code is:

    Traceback (most recent call last):
    File "C:\Documen ts and Settings\Smythv ille\My Documents\Pytho n\Stuff\Ch4\ex1-6.py", line 59, in <module>
    a = int(raw_input(" \nTry a number!"))
    ValueError: invalid literal for int() with base 10: 'six'

    [CODE=python]
    a = int(raw_input(" \nTry a number!"))

    try:
    if a >= 0 and a <= 9:
    print "\nYour number is between or equal to 0 and 9."
    else:
    print "\nYour number is not between or equal to 0 and 9."
    except ValueError:
    print "Could not convert data to an integer."
    [/CODE]
    Even though I have specified the ValueError is doesn't catch it.

    Any Ideas?

    Thanks

    Eclipse
    Move the first line of code inside the try block.

    Comment

    Working...