This post first appeared on my old C++ blog. You might have seen it before.
I think by now we can all agree that exceptions are generally a good thing in C++. They allow us to separate the error handling from the general flow of control inside a program and also enable us to handle errors at the most appropriate point. More often than not, the best point to handle errors is quite far removed from the source of the exception.
Imagine my surprise when I came across the following gem that was almost worthy of the Daily WTF:
I guess in some circles, being able to throw any sort of POD or object as an exception is considered a good thing. It's not necessarily something I consider a good idea. For the moment we'll also gloss over the advisability of catching exceptions by value. That doesn't mean I'm condoning that sort of coding, especially not when you're catching types that might trigger memory allocations when copied.
But wait, it gets better. You thought that the code snippet above was part of a larger chunk of code that I omitted, didn't you? Well, it actually wasn't - it was all parked in a header file. Obviously in the interests of brevity I removed the code that actually handled the exceptions while preserving the full structure of the code in the header file.
So what the heck is going on here then? It looks like in order to avoid duplication of code - always a worthy goal - the above header file got include wherever "needed", so at least one of the project's source files was full of code like this:
Pass the Stroustrup, I need to refactor a developer or three...