Question

Can anyone please confirm me if this information is correct or not:

In C++, inside catch block we can re-throw an exception using throw statement, but the thrown exception should have the same type as the current caught one.

Was it helpful?

Solution 2

The rethrown exception can have a different type. This compiles and runs correctly on VS2012:

#include <iostream>

int main() try
{
    try
    {
        throw 20;
    }
    catch (int e)
    {
        std::cout << "An exception occurred. Exception Nr. " << e << std::endl;
        throw std::string("abc");
    }
}
catch (std::string const & ex)
{
    std::cout << "Rethrow different type (string): " << ex << std::endl;
}

Output:

An exception occurred. Exception Nr. 20
Rethrow different type (string): abc

OTHER TIPS

throw; all by itself in a catch block re-throws the exception that was just caught. This is useful if you need to (e.g.) perform some cleanup operation in response to an exception, but still allow it to propagate upstack to a place where it can be handled more fully:

catch(...)
{
   cleanup();
   throw;
}

But you are also perfectly free to do this:

catch(SomeException e)
{
   cleanup();
   throw SomeOtherException();
}

and in fact it's often convenient to do exactly that in order to translate exceptions thrown by code you call into into whatever types you document that you throw.

Not necessarily. As soon as you catch it, it is up to you what to do with it. You can either throw an exception that is the same or a completely new exception. Or, not do anything at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top