How to catch exceptions elegantly in this situation?

Brian van den Broek bvande at po-box.mcgill.ca
Fri Oct 8 01:22:23 EDT 2004


Saqib Ali said unto the world upon 2004-10-07 23:13:
> Check out the following code fragment
> 
> Line  1: myDict = {}
> Line  2: a = 5
> Line  3: b = 2
> Line  4: c = 0
> Line  5: myDict["A"] = a + b + c
> Line  6: myDict["B"] = a - b - c
> Line  7: myDict["C"] = a * b * c
> Line  8: myDict["D"] = a / b / c
> Line  9: myDict["E"] = a ** b ** c
> Line 10: ...<etc>...
> Line 11: ...<etc>...
> Line 12: ...<etc>...
> 
> An exception will be raised at line #7 because of division by zero.
> I want the exception to be caught, printed, but then I want the flow
> to continue to line #8 and onwards. I want this behaviour on EACH
> assignment line. (Line 5 onwards). IE: Do the assignment. If an
> exception is raised, print the exception and continue to the next
> assignment.
> 
> I can't think of an elegant way to handle this. Can someone help?
> 
> - I COULD surround each assignment line with a try/except block. But
> that seems very tedious, cumbersome and unwieldy.
> 
> - Alternatively I tought of writing a function 'myFunc' and passing in
> the args as follows: (dict=myDict, key="D", expression="a / b / c"). I
> figured within 'myFunc' I would do:  myDict[key] = eval(expression)
> .......... However that wouldn't work either because the eval would
> fail since the variables will be out of context.
> 
> Any Suggestions??
> 
> -Saqib

Hi Saqib,

I'm still learning and my skills are modest, so I'm posting this as much 
to learn what is wrong with it as to offer help to you. But what about:

 >>> a = 1
 >>> a = 5
 >>> b = 2
 >>> c = 0
 >>> my_dict = {}
 >>> key_list = ['A', 'B', 'C']
 >>> value_list = ['a + b +c', 'a / b / c', 'a - b - c']
 >>> dict_ingredients = zip(key_list, value_list)
 >>> for (k, v) in dict_ingredients:
... 	try:
... 		my_dict[k] = eval(v)
... 	except ZeroDivisionError:
... 		pass
... 	
 >>> my_dict
{'A': 7, 'C': 3}
 >>>




More information about the Python-list mailing list