Reputation: 759
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
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
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
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