When to use exceptions (was Re: reducing if statements...)

Christian Tanzer tanzer at swing.co.at
Wed Aug 22 07:29:24 CEST 2001


skip at pobox.com (Skip Montanaro) wrote:

> Also, note that you can have your cake and eat it too, because you can (and
> many modules do) raise an exception and annotate it with messages or error
> codes:
> 
>     try:
>         somemodule.func(p1, p2, p3)
>     except somemodule.Error, (code, msg):
>         if code == 200:
>             # an expected condition, warn and move on
>             print msg
>         else:
>             # something we can't recover from - reraise the exception
>             raise

I'd rather use:

    try:
        somemodule.func(p1, p2, p3)
    except somemodule.Error_foo, msg :
        print msg
        ...
    except somemodule.Error_bar, msg :
        ...
    ### no need for raise anymore

Much clearer and easier to use. 

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list