handling errors

Robin Munn rmunn at pobox.com
Thu Jun 5 11:04:28 EDT 2003


ataraxia2500 <messageboardfan1 at yahoo.com> wrote:
> I got that little piece of code on a tutorial. I want to add an error
> handling to the print_menu function so that if the user enter strings
> instead of int the program doesn't crash but I couldn't make it. I tried to
> add: "except ValueError:
>         print "That was not a number.""
> at the end but it didn't do anything. any idea how I should use it?

Sounds like you forgot the "try" part of the "try ... except" block.
Here's how it's supposed to work:

try:
    code_that_could_fail()
except SomeError:
    handle_error()
keep_going()

So, for example, here's how you would want to ask for a number:

value = None
while value is None:
    line = raw_input()  # Much safer than input()
    try:
        value = int(line)
    except ValueError:
        print "That was not a number."
print "You entered the number", value

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list