473,386 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

avoiding nested try/excepts

So I have code that looks something like this:

def f(xs):
for x in xs:
y = g(x) # can raise exception AnException
for z in h(y):
k(z) # can raise a variety of exceptions

Now, if g(x) raises AnException, I want to log something and skip the
inner loop (but continue with the outer loop). If k(z) raises an
exception, I want to log something and then re-raise the exception to
exit all the way out of f. Currently I do something like:

def f(xs):
for x in xs:
try:
y = g(x)
for z in h(y):
k(z)
except AnException, e:
log(x, e)
except:
log(x)
raise

I've heard before that it's generally a good idea to try to localize
your try-except blocks as much as possible. This would lead me to do
something like:

def f(xs):
for x in xs:
try:
y = g(x)
except AnException, e:
log(x, e)
else:
for z in h(y):
try:
k(z)
except:
log(x)
raise

but now I have another level of nesting and things get kinda hard for me
to read. So I have two questions:

(1) Should I really worry about localizing try-except blocks? and, if so
(2) Is there a cleaner way to do this kind of thing?

Note that I can't edit the g or k functions, so I can't move the
try-except blocks inside.

Thanks,

Steve
Jul 18 '05 #1
3 2171
Steven Bethard <st************@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:an*@doxdesk.com
http://www.doxdesk.com/
Jul 18 '05 #2
Steven Bethard wrote:
(1) Should I really worry about localizing try-except blocks? and, if so
Not when the error-handling doesn't take advantage of the greater locality.
(2) Is there a cleaner way to do this kind of thing?
I've always thought that catching an exception was the clean way that
replaces dealing with functions returning error codes.
Note that I can't edit the g or k functions, so I can't move the
try-except blocks inside.


If you cannot modify, you can still wrap them:
def catch(*exceptions): .... def make_catcher(f):
.... def catcher(*args):
.... try:
.... return f(*args)
.... except exceptions:
.... print "caught it"
.... return catcher
.... return make_catcher
.... @catch(ZeroDivisionError) .... def f(a, b): return a / b
.... f(1, 2) 0 f(1, 0) caught it


You may guess at what line in the above it dawned on me that you'd be better
off with individual wrappers than a generalized decorator...

Peter
Jul 18 '05 #3
Andrew Clover wrote:
Steven Bethard <st************@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.)


So what's the idiom for catching all exceptions *except*
MemoryError/KeyboardInterrupt/SystemExit? Too bad we won't get our new
Exceptions hierarchy until Python 3000...

Steve
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Andy Baker | last post by:
Hi there, I'm learning Python at the moment and trying to grok the thinking behind it's scoping and nesting rules. I was googling for nested functions and found this Guido quote:...
6
by: B0nj | last post by:
I've got a class in which I want to implement a property that operates like an indexer, for the various colors associated with the class. For instance, I want to be able to do 'set' operations...
8
by: Robert W. | last post by:
I've almost completed building a Model-View-Controller but have run into a snag. When an event is fired on a form control I want to automatically updated the "connnected" property in the Model. ...
8
by: Mike Mascari | last post by:
Hello. I have a query like: SELECT big_table.* FROM little_table, big_table WHERE little_table.x = 10 AND little_table.y IN (big_table.y1, big_table.y2); I have indexes on both big_table.y1...
1
by: Tomas Sieger | last post by:
Hi all, I'm in doubt with the following code: class Base { public: class Nested {}; }; class Derived:public Base { public: class Nested {
77
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop....
5
by: Frederick Gotham | last post by:
I have a typedef in a base class, and I want it to effortlessly filter through to the derived class. Here's a quick example: class Base { public: typedef unsigned SpecialType; };
3
by: n.torrey.pines | last post by:
Hi I work with a nested tree-like data structure template (that happens to be a tuple of vectors of tuples of trees of something, with different tuple elements having different types) I need...
3
by: jdurancomas | last post by:
Dear all, I'm trying to declare the operator++ to a nested class. The nested class is not template but the container it is. The code used in teh sample program is included bellow: ...
17
by: Tony Jackson | last post by:
Hi I'm quite new to C programming - I have more of a Java background: maybe someone here can advise me. I'm nearly finishing a little program but it has some hard-to-find bugs that basically...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.