Wednesday, November 5, 2008

More on soft exceptions

I had a real-world problem just now which I chose to tackle using soft exceptions. I have a series of rules which transform a data object. Depending on the state of the data object, not all the rules are applicable. Also, depending on the rule, it may or may not be critical to have the rule applied to the data object.

While pursuing another task, I caused an exception inside a method which applied one of these rules. Rather than simply track back the exception and add more handling to the code, I decided to *also* wrap this rule in a soft exception handler. In operations, it would be far better to simply not apply the rule than to cease processing and crash, yet the rule logic is written such that any error causes a program fault.

Ideally, I would implement the soft exception handling using a logger level which could be applied application-wide, but that is a bigger task than I wanted to tackle in 10 minutes!

So, I wrote:


exceptionMode = "Soft"

try:
originalState = object.state
// Apply rule logic

except:
object.state = originalState

if exceptionMode == "Soft":
print "NEW WARNING -- generated in MyClass.methodName
print "Methodname failed. Original state is being used."
traceback.print_exc()
print "END WARNING"

else:
raise

return successFlag


This worked beautifully! I can check the code in with soft exceptions turned on, so that in operations any bugs here will only result in a rule failure, not a complete process failure. However, I still have access to the full stack trace through logging and can also set the exception mode to "Hard" (or anything that's not "Soft") and have 'brittle' behaviour for testing.

Score 1 for soft exceptions!

Clearly, it would be ideal to log instead of print. It would be good to have have the following logging controls:
* Hard or soft exception handling
* A logging level which would actually bring up user warning dialogs
* A variety of logging detail levels

Cheers,
-T