Help needed: try/except -idiom vs. C-style coding
Robert Brewer
fumanchu at amor.org
Mon Oct 11 11:34:55 EDT 2004
pekka niiranen wrote:
> I have defined function that calls another functions like this
> (modified for this mail):
>
> def main_function():
> if not function1():
> m = "main_function: function1 failed"
> print_error(m)
> return False
> if not function2():
> m = "main_function: function2 failed"
> print_error(m)
> return False
> if not function3():
> m = "main_function: function3 failed"
> print_error(m)
> return False
> return True
>
> In book "Learning Python 1st edition" is was said
> that this C-style programming is bad practice
> and should be replaced with structure:
>
> def main_function():
> try:
> function1():
> function2():
> function3():
> except:
> what_ever()
> return False (?)
> else:
> return True (?)
>
> How can I use try/except -style if I want to know WHICH
> of functions 1-3 failed in try: -section and print
> that information? What should functions return in order to
> a) raise an exception and
> b) tell main_function "it was me who failed for this reason"
> This message should be user specific.
If you care which function failed, you should narrow the exceptions:
def main_function(a, b, c):
try:
function1(a)
except IndexError:
print "function1 failed"
return False
try:
function2(b)
except IOError:
print "function2 failed"
return False
try:
function3(c)
except (TypeError, ValueError):
print "function3 failed"
return False
return True
It's also good practice to specify which errors you expect as above;
bare "except:" has its place, but it's a rare one.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list