Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception rethrowing

Tags:

c++

What is the difference between:

foo();

and

try{
    foo();
} catch (...){
    throw;
}

As I understand - if there is no try-catch block in function that calls foo() - the exception will be caught by try-catch block of outside function(if there is any). Am I right in this?

But what if there is a try-catch block in function that calls foo(), but there is no catcher who can handle it - must I write catch (...) { throw; } to let it be caught by someone outside it? Is it necessary?

like image 340
Alexey Teplyakov Avatar asked Feb 24 '26 05:02

Alexey Teplyakov


1 Answers

A throw-expression with no operand rethrows the exception being handled. [§15.1/8]

So there are the same in practice.

 

the exception will be caught by try-catch block of outside function(if there is any). Am I right in this?

Yes.

 

But what if there is a try-catch block in function that calls foo(), but there is no catcher who can handle it - must I write catch (...) { throw; } to let it be caught by someone outside it? Is it necessary?

Handle exceptions which is expected you handle them in the calling point and leave the others. You don't have to re-throw them. If no catcher, catches the exception finally std:terminate will be invoked.

try
{
    foo();
}
catch (YourExpectedException &ex)
{
  // ...
}
catch (...)    \
{               \
                 > // You don't need this kind of re-throwing
    throw;      /
}              /
like image 84
masoud Avatar answered Feb 26 '26 18:02

masoud



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!