Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested try-catch blocks?

int main ()
{
    try
    {
        try
        {
            throw 5;
        }
        catch (int n)
        {
            throw;
        }
    }
    catch (...)
    {
        cout << "Exception occurred";
    }
}

This prints out "Exception occured" but

int main ()
{
    try
    {
        try
        {
            throw;
        }
        catch (...)
        {
            throw;
        }
    }
    catch (...)
    {
        cout << "Exception occurred";
    }
}

This just errors. It seems like I'm doing the try-catch's exactly the same! The only difference is that in the first case I'm throwing an int, then a general exception, but in the second case, I'm throwing a general exception both times. Is the program confused as to which catch to go to?

like image 593
newprogrammer Avatar asked Jan 28 '26 06:01

newprogrammer


1 Answers

There's no such thing as "general exception" and you throw no such thing.

In the first example, you throw an int, then you re-throw the exception that you are handling. That's the meaning of throw without an argument.

In the second example you start with an attempt to re-throw an exception that you are handling. As you are not handling an exception at that time, you get an error.

like image 110
n. 1.8e9-where's-my-share m. Avatar answered Jan 30 '26 18:01

n. 1.8e9-where's-my-share m.



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!