Help needed: try/except -idiom vs. C-style coding

Robert Brewer fumanchu at
Mon Oct 11 17:34:55 CEST 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):
    except IndexError:
        print "function1 failed"
        return False
    except IOError:
        print "function2 failed"
        return False
    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
Amor Ministries
fumanchu at

More information about the Python-list mailing list