Yuan Wen
Yuan Wen

Reputation: 1701

what exceptions can "try catch(...)" catch in c++?

The code

    try{
        memcpy(p, buf, l);
    }
    catch (...){
        ofstream f("memcpy.error");
        f << "memcpy.error";
    }

if p is null,memcpy will throw exception,but catch(...)can't catch it.So,in c++,what do try catch(...) actually do?

Upvotes: 0

Views: 2093

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

Re

what exceptions can “try catch(...)” catch in c++?

It can catch any exception produced by a C++ throw.

Note by the way that the ellipsis ... needs to be three periods, not the Unicode ellipsis character, otherwise the compiler will choke on it!


Re the code

buf = nullptr;
try{
    memcpy(p, buf, l);
}
catch (...){
    ofstream f("memcpy.error");
    f << "memcpy.error";
}

The call of memcpy here has formal undefined behavior.

However, a particular C++ implementation can define any behavior, including that which is formally UB, and your compiler Visual C++ may do that, possible with special options. However, Microsoft's documentation of memcpy does not mention such more well-defined behavior.

On the third hand, undefined behavior includes that you might get some behavior that you erroneously expected, such as the execution going into the catch clause.


In the 1990's, Microsoft's Visual C++ would catch Windows SEH exceptions (a lower level kind of exception) in catch(...), by default. For example, you can get an SEH exception by dereferencing a nullpointer, which might happen in your memcpy call. Happily the compiler no longer has catching of such exceptions as default, but you can specify that behavior by using the _set_se_translator function.

Upvotes: 2

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

If p is null, memcpy will throw an exception.

Incorrect. If either pointer is null, it is undefined behavior. Since undefined is "undefined", there isn't much you can do about it when it happens (in a non-implementation dependent way).

Upvotes: 1

dxiv
dxiv

Reputation: 17638

Answering in the context of the question being tagged as [visual-studio] and [winapi] by implication.

try/catch blocks catch C++ exceptions, while memcpy with a NULL destination throws a Win32 structured exception.

You can catch those exceptions with __try/__except blocks (Structured Exception Handling).

Alternatively, you can convert them to C++ exceptions catchable in C++ try/catch blocks via _set_se_translator.

Upvotes: 3

Related Questions