Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

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();
  }
}
like image 204
Merad Avatar asked Jan 28 '26 02:01

Merad


2 Answers

Yes. (have to fill to reach 30 characters)

like image 128
Pete Becker Avatar answered Jan 29 '26 15:01

Pete Becker


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.

like image 34
Justin Niessner Avatar answered Jan 29 '26 15:01

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!