C++ FAQ Celebrating Twenty-One Years of the C++ FAQ!!!
(Click here for a personal note from Marshall Cline.)
Section 17:
[17.7] I have too many try blocks; what can I do about it?

You might have the mindset of return codes even though you are using the syntax of try/catch/throw. For instance, you might put a try block around just about every call:

void myCode()
{
  try {
    foo();
  }
  catch (FooException& e) {
    ...
  }

  try {
    bar();
  }
  catch (BarException& e) {
    ...
  }

  try {
    baz();
  }
  catch (BazException& e) {
    ...
  }
}
Although this uses the try/catch/throw syntax, the overall structure is very similar to the way things are done with return codes, and the consequent software development/test/maintenance costs are basically the same as they were for return codes. In other words, this approach doesn't buy you much over using return codes. In general, it is bad form.

One way out is to ask yourself this question for each try block: "Why am I using a try block here?" There are several possible answers:

  • Your answer might be, "So I can actually handle the exception. My catch clause deals with the error and continues execution without throwing any additional exceptions. My caller never knows that the exception occurred. My catch clause does not throw any exceptions and it does not return any error-codes." In that case, you leave the try block as-is — it is probably good.
  • Your answer might be, "So I can have a catch clause that does blah blah blah, after which I will rethrow the exception." In this case, consider changing the try block into an object whose destructor does blah blah blah. For instance, if you have a try block whose catch clause closes a file then rethrows the exception, consider replacing the whole thing with a File object whose destructor closes the file. This is commonly called RAII.
  • Your answer might be, "So I can repackage the exception: I catch a XyzException, extract the details, then throw a PqrException." When that happens, consider a better hierarchy of exception objects that doesn't require this catch/repackage/rethrow idea. This often involves broadening the meaning of XyzException, though obviously you shouldn't go too far.
  • There are other answers as well, but the above are some common ones that I've seen.

Main point is to ask "Why?". If you discover the reason you're doing it, you might find that there are better ways to achieve your goal.

Having said all this, there are, unfortunately, some people who have the return-code-mindset burned so deeply into their psyche that they just can't seem to see any alternatives. If that is you, there is still hope: get a mentor. If you see it done right, you'll probably get it. Style is sometimes caught, not just taught.