Pythonic API design: detailed errors when you usually don't care
Paul Rubin
http
Mon Oct 2 14:02:52 EDT 2006
Steve Holden <steve at holdenweb.com> writes:
> I should have thought the simplest spelling of your requirements would be
>
> try:
> do_something()
> print "It worked"
> except:
> # it didn't
This usage is generally disparaged because of the possibility of
exceptions having nothing to do with do_something, including
asynchronous exceptions like KeyboardInterrupt, that really should get
handed up to higher levels of the program.
An approach not mentioned is for do_something to arrange that its
"expected" exceptions would all belong to subclasses of some single
class, so you could catch all those exceptions at once:
try: do_something()
except SomethingException:
# it didn't work
or alternatively you could break out the individual subclasses:
try: do_something()
except SomethingHTTPException:
# it didn't work for this reason
except SomethingWhatsitException:
# or that one
Or alternatively you could just put everything in one exception
with the underlying exception in the returned arg:
try: do_something()
except SomethingException, e:
# it didn't work, e gives the reason
...
def do_something():
try:
do_something_1() # do the real something
except (HTTPError, ApplicationError, ...), e:
# pass detailed exception info up to the caller
raise SomethingException, (sys.exc_info(), e)
More information about the Python-list
mailing list