How to catch exceptions elegantly in this situation?

Saqib Ali syed_saqib_ali at yahoo.com
Thu Oct 7 23:13:06 EDT 2004


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



More information about the Python-list mailing list