user1234369
user1234369

Reputation: 21

What will happen is an exception is thrown while executing a throw statement

I have following code snippet:

try
{
    if(/*something is true*/)
    {  
       throw Win32Error(msgWin32Error->GetError()); //assume msgWin32Error is NULL
    }
}
catch (Win32Error& win32Error)
{

}

Assuming msgWin32Error is NULL in above code snippet, when throw statement gets executed, it will have another exception in turn. What will be the behavior in such circumstance?

Thanks, Su

Upvotes: 0

Views: 101

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

First of all, when you dereference a NULL pointer, you get undefined behavior. An exception might be thrown (because throwing an exception is in the list of allowable behaviors if UB is invoked), but you can't count on that. However, it's easy to construct a well defined example that gets at what I think you are asking.

char const* foo()
{
    throw ExceptionZ();
    return "message";
}

void bar()
{
    try
    {
        throw ExceptionX(foo());
    }
    catch(ExceptionX) { ... }
    catch(ExceptionZ) { ... }
}

In this case, the handler for ExceptionZ will be entered. The throw statement in bar does not complete. The exception thrown from foo() propagates before it can.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

There will be no C++ exception here.

You are conflating two things:

  • C++ exceptions (see: throw, try, catch)
  • Runtime errors invoked by the operating system (e.g. segmentation fault)

The latter are sometimes also confusingly called "exceptions", but you cannot catch these with C++ catch.

What will happen is that the dereference of msgWin32Error will (probably) cause the Operating System to terminate your application. Control will never even reach your throw instruction.

Upvotes: 4

Related Questions