The Lone C++ Coder's Blog

The Lone C++ Coder's Blog

The continued diary of an experienced C++ programmer. Thoughts on C++ and other languages I play with, Emacs, functional, non functional and sometimes non-functioning programming.

Timo Geusch

2-Minute Read

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:

  catch (std::string ex) {
    // Do something horrible with the exception
  }
  catch (const char *ex) {
    // Eh?
  }
  catch (int i) {
    // Uh oh
  }

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:

void doSomething() {
  try {
    // Lots of processing that might throw
  }
  #include "catch_clauses.H"
}

Pass the Stroustrup, I need to refactor a developer or three…

Recent Posts

Categories

About

A developer's journey. Still trying to figure out this software thing after several decades.