Imperative exceptions

Posted on January 07, 2015 · 1 min read · tagged with: #API #design #exceptions #libraries

If you develop software in .NET, you probably use exceptions. Or at least, handle them, even by simply logging. Beside providing an easy way to deal with runtime errors, exceptions are frequently met during the initial phase of using a library or a framework, when you don’t know API yet and try to do something the other improper way. Consider one of the exceptions: KeyNotFoundException. It’s thrown by a dictionary when your program tries to get the key which hasn’t been added. The question what should you do when you encounter this error. The truth is that the message of this exception isn’t descriptive enough. It simply states that:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

This doesn’t provide y ou any meaningful information. After getting this exception, you still don’t know what key was missing. I’d prefer to get the missing key, event as a string representation. Later on, when the exception is logged, one can tell what was missing. But that’s only a prelude. What about cases when you receive the meaningful and well-described exception like:

You haven’t registered any handler for this event

Does it help you to solve this problem? If you know the library and you met this exception before, it’ll be easy to fix. What if it’s your first encounter? Then, providing an imperative part like:

You haven’t registered any handler for RoomBooked event. Register handler using bus.Register(hander)

is extremely helpful and lets a developer to maintain the focus on the code rather than switching to searching through StackOverflow.


Comments

Completely agree - another set of meaningless exceptions are those from SQL Server, such as: "String or binary data would be truncated" or "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM." with no info which field caused the error.

by Sebastian Solnica at 2015-01-07 12:38:53 +0000

At minimum, just log full stack trace. If you can't - but on the other hand, why can't you? But if you can't one must corelate exception with some other logs (web server timestamp log, Event log-Windows/Application/ logs etc.

In my experience, you can write few orseveral or even many exception handlers. In the long run it is pointless, there is too much to cover. Better focus on general handler with good stacktrace and few real good base cases.

by ChaosEngine at 2015-01-07 16:12:08 +0000

It's not about handlers, it's about exception content and the intent of the thrower. For instance, if you throw an db exception, just add a description for it to let another one handle it easily.

by scooletz at 2015-01-08 09:13:28 +0000

Agree, that one (SqlEx) is good example for specific handling

by ChaosEngine at 2015-01-08 12:06:40 +0000