Is this the *right* way of exception handling?

Alex Martelli aleaxit at yahoo.com
Sat Aug 4 03:08:56 EDT 2001


"Quinn Dunkan" <quinn at retch.ugcs.caltech.edu> wrote in message
news:slrn9mn482.9od.quinn at retch.ugcs.caltech.edu...
    ...
> Python provides two ways to do the same thing:
>
> if not foo: raise bar
>
> and
>
> assert foo
>
> The difference is that asserts can be turned off.  I use asserts to
describe

Actually, as you mention later, three ways, since you can write:

if __debug__:
    if not foo: raise bar

and now you have the exact semantic equivalent of an assert, in
terms of being able to turn it off (it's turned off in the same way:
a -O or -OO switch to Python).  Note that 'if __debug__ and not foo'
doesn't work the same way (not currently, at least).


> Python style is often to just toss the data in, and see if it's good by
> whether it blows up or not (the "better to ask forgiveness" philosophy),
but
> it can be handy to catch things before that point, especially when the
> consistency of a filesystem or database is at stake.  And sometimes those
> checks can be very expensive, so it's handy to be able to turn them off
when
> everything's been tested.

I agree, see:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291


> On the other hand, if it's a "bug" error, you usually shouldn't be
catching
> it, so it shouldn't be an ordinary exception type.  I dunno.  In any case,
I'm

In a long-running program that dynamically loads code, you may
have to keep running (and not corrupt state) even if a buggy
piece of code has been loaded.  Ditto for an application that allows
add-ons -- it may be unacceptable to let a buggy add-on crash
the main app (or lead to corrupted state, which can be even worse).


Alex






More information about the Python-list mailing list