27

Consider the following C++ code:

try {
  throw foo(1);
} catch (foo &err) {
  throw bar(2);
} catch (bar &err) {
  // Will throw of bar(2) be caught here?
}

I would expect the answer is no since it is not inside the try block and I see in another question the answer is no for Java, but want to confirm C++ is also no. Yes, I can run a test program, but I'd like to know the language definition of the behavior in the remote case that my compiler has a bug.

WilliamKF
  • 41,123
  • 68
  • 193
  • 295

3 Answers3

29

No. Only exceptions thrown in the associated try block may be caught by a catch block.

Puppy
  • 144,682
  • 38
  • 256
  • 465
9

No, It won't, An enclosing catch block upwards the hierarchy will be able to catch it.

Sample Example:

void doSomething()
{
    try 
    {
       throw foo(1);
    } 
    catch (foo &err) 
    {
       throw bar(2);
    } 
    catch (bar &err) 
    {
       // Will throw of bar(2) be caught here?
       // NO It cannot & wont 
    }
}

int main()
{
    try
    {
        doSomething();
    }
    catch(...)   
    {
         //Catches the throw from catch handler in doSomething()
    }
    return 0;
}
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    Should improve the answer that `bar(2)` will be caught in catch block in `main()` function. This will make the answer more clear. – zar Apr 11 '17 at 20:15
2

No, a catch block handles the nearest exception, so if you try ... catch ( Exception &exc ) ... catch ( SomethingDerived &derivedExc ) the exception will be handled in the &exc block

You might achieve the desired behaviour by exception delegation to the calling method

Wizz
  • 1,267
  • 1
  • 13
  • 20