avoiding nested try/excepts

Andrew Clover and-google at doxdesk.com
Fri Nov 19 13:16:24 CET 2004

Steven Bethard <steven.bethard at gmail.com> wrote:

>          except:
>              log(x)
>              raise

(Of course 'except:' is rarely a good idea! You probably want to
exclude at least MemoryError - as log() might then fail - and possibly
also KeyboardInterrupt, SystemExit depending on what you're doing.)

> but now I have another level of nesting and things get kinda hard for me 
> to read.

I find it fine - I prefer it to the shorter version as it's clearer
where AnException is expected to be raised.

In general, localising exception handling is a good move, and I'd
personally do so in the case of your example. If g() is the only
method that can possibly raise AnException the shorter version is
safe, but otherwise botched exception handling can be a real pain to
track down.

If you find the nesting level a bit much you could always use fewer
whitespaces. :-)

Andrew Clover
mailto:and at doxdesk.com

More information about the Python-list mailing list