CodeSOD: An Exceptional Zero

One of the most powerful features of using exceptions for error handling is that they let you create your own exceptions, and thus accurately describe the family of exceptional situations your code could generate. On the flip side, some developers over-specialize, creating custom exceptions for every different place an out-of-range error could happen, for example.

Then there's the code Nasch was debugging recently. The previous developer found a different way to create unique exceptions for every place an error might occur.

if (SwiftContextFactory.getInstance().generateWireCanonicalSendException)
	// Do some other things
} catch (Throwable t) {
	log.error("Couldn't send wire message to SWIFT", t)
	// Other error condition things

The code in question here is Groovy, but it could be nearly any other OO language.

This block here is representative of a pattern that appears all over the codebase. When an exceptional situation occurs, divide by zero, then log the error. The Throwable object itself will contain the details of the divide by zero, including the numerator- which means it's "easy" to generate a unique error code for anything that can go wrong: just divide something else. 7/0 or 11/0 or 432/0. Now it's easy to know where an error originated, just search the codebase for 6/0.

In addition to this creative way to create unique errors, I have to puzzle over the elision: Do some other things. This implies that Nasch skipped some code which came after the divide by zero error- code that would never execute.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *