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

pekka niiranen pekka.niiranen at wlanmail.com
Mon Oct 11 13:58:16 CEST 2004


Hi there,

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.

Note that main_function might also be subroutine and must
information of its failure to its upper level.

I am looking something like:

def main_function():
     try:
	function1():
	function2():
	function3():
     except: !!!! FIX !!!!!
	print "Function %s failed in main_function" % functions_name			print 
"Reason: %s" % functions_error_message

Does try/except -idiom expect that message
'"print "Reason: %s" % functions_error_message'
is always printed at the function itself, not by
its caller's except : -section?

-pekka-



More information about the Python-list mailing list