Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-throw an exception inside catch block

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.

like image 566
Naruto Biju Mode Avatar asked May 02 '14 22:05

Naruto Biju Mode


People also ask

Can we're-throw exception in catch block?

When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). Or, wrap it within a new exception and throw it.

What would happen if an exception is thrown inside of a catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

Can exceptions be re thrown?

When an exception is caught, we can perform some operations, like logging the error, and then re-throw the exception. Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

Can we Rethrow exception in catch block in Java?

If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.


2 Answers

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.

like image 95
dlf Avatar answered Sep 18 '22 14:09

dlf


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
like image 23
Gabriel Avatar answered Sep 19 '22 14:09

Gabriel