Meaningful Exceptions

There are many APIs which on error throw exceptions. Or we write wrappers that turn error codes into exceptions. At think-cell, we have macros that check Windows API and COM calls for errors and on failure, throw an exception wrapping an HRESULT.

Is that a good idea? If you catch the exception very close to the callsite, why bother using an exception at all? Throwing an exception is slow on most platforms, and instead, you can just check the return value without wrapping it into an exception.

This leaves the case where the exception is caught further away, for example in the calling function. But there, the wrapped error code really has no meaning anymore. If you get an E_ACCESSDENIED, what was it that you got denied access to? It is alluring to make inferences about which operation failed based on the error code, simply because that is the only information available: "If it is E_ACCESSDENIED, then this is probably coming from opening the xyz file." But of course, this is neither certain nor self-documenting.

That‘s why we recently moved away from wrapping local errors into exceptions by default. Likewise, in my opinion, the standard library exceptions are of questionable value.

I am not saying that exceptions are bad. But we should ensure that they carry enough semantics to be meaningful. If an operation fails, and you want to throw, define a dedicated exception type that carries the semantics you want, like „opening the xyz file failed“, and throw that instead of letting some meaningless low-level exception escape the context in which it makes sense.

— by Arno Schödl

Do you have feedback? Send us a message at devblog@think-cell.com !

Sign up for blog updates

Don't miss out on new posts! Sign up to receive a notification whenever we publish a new article.

Just submit your email address below. Be assured that we will not forward your email address to any third party.

Please refer to our privacy policy on how we protect your personal data.

Share