Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `catch` catch the throw here?

Tags:

c++

try-catch

I'm not really sure what's happening here. Its obvious why the inner catch catches throw 2, but why does the outher catch(int x) catch throw? I thought catch(int x) is supposed to catch integer values only. Is it possible that the second throw throws what was first cought (which is 2)?

try
{
    try
    {
        throw 2;
    }
    catch (int n)
    {
        std::cout << "Inner Catch " << n << std::endl;
        throw;
    }
}
catch (int x)
{
    std::cout << "Outer Catch " << x << std::endl;
}

Thanks!

like image 595
user3265447 Avatar asked Jan 24 '23 07:01

user3265447


1 Answers

You cannot throw nothing. throw; alone can be used in a catch-block to rethrow the currently handeled exception. From cppreference:

Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls std::terminate if used otherwise). The catch clause associated with a function-try-block must exit via rethrowing if used on a constructor.


I thought catch(int x) is supposed to catch integer values only

Thats what it does.

Is it possible that the second throw throws what was first cought (which is 2)?

Exactly that.

like image 152
463035818_is_not_a_number Avatar answered Jan 26 '23 21:01

463035818_is_not_a_number