Merad
Merad

Reputation: 759

Is it valid to throw in a catch block (C++)?

I haven't done C++ in a while and my memory is fuzzy, nor have I found a definitive answer so far searching. I'm not talking about rethrowing the caught exception, but rather catching one exception and throwing a different type, such as:

std::unordered_map<int, int> foo;
...
int getFoo(int id)
{
  try {
    return foo.at(id);
  }
  catch (std::out_of_range& e)
  {
    throw MyMoreDescriptiveExceptionType();
  }
}

Upvotes: 2

Views: 1960

Answers (4)

Peter Bloomfield
Peter Bloomfield

Reputation: 5766

Yes, it's entirely valid. It's actually quite a common thing to do. For example, a small utility class may throw a fairly generic exception. The code that was calling it may catch that exception, and wrap it in a more specific one, providing more useful information about the context. It will then throw that 'outer' exception.

The same catch-wrap-throw pattern can extended as many levels as you need, until something is able to address the problem or shutdown gracefully.

Upvotes: 3

aks
aks

Reputation: 167

Yes and that thrown exception will be caught by the next catch in order or next upper level catch and so on

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245519

Yes. Among other things, it allows you to log and re-throw exceptions properly.

Just be careful to re-throw properly. If done incorrectly, you could lose the original stack trace which makes the actual problem much harder to track down.

Upvotes: 4

Pete Becker
Pete Becker

Reputation: 76523

Yes. (have to fill to reach 30 characters)

Upvotes: 7

Related Questions