How to catch exceptions elegantly in this situation?
Steve Holden
steve at holdenweb.com
Wed Oct 13 20:37:34 EDT 2004
Saqib Ali wrote:
> 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??
>
Read the recent thread on resumab le exceptions: it isn't available
right now, and it doesn;t seem likely to be.
regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
More information about the Python-list
mailing list