简体   繁体   中英

How to cause C++ throw to dump core if the exception would be handled by a particular catch block

Is there a way to cause a throw in C++ to dump core at the throw site if the thrown exception would be handled by a certain catch block? I would like something similar to what happens with g++ when an exception reaches the top level.

For example, I would like something like this:

try {
  bar();
  try {
    foo();
  } catch(...) {
#  pragma dump_at_throw_site
  }
} catch(...) {
  std::cerr << "There was a problem" << std::endl;
}

This way, if any exception thrown from foo() or its callee's that reaches the call-site of foo() would cause a core dump at the throw site so one can see who threw the exception that made it to the to this level.

On the other hand, exceptions thrown by bar() would be handled normally.

Yes,it can in Windows. I don't know Linux, suppose it can also.

We can register a Exception Handler function to response the throw before the catch Here is the code example:

#include <iostream>
#include "windows.h"
#define CALL_FIRST 1
LONG WINAPI
VectoredHandler(
    struct _EXCEPTION_POINTERS *ExceptionInfo
    )
{
    UNREFERENCED_PARAMETER(ExceptionInfo);
    std::cout <<"VectoredHandler"<<std::endl;
    return EXCEPTION_CONTINUE_SEARCH;
}
int main()
{
    PVOID handler;
    handler = AddVectoredExceptionHandler(CALL_FIRST,VectoredHandler);

    try {
        throw 1;
    }catch(...)
    {
        std::cout <<"catch (...)"<< std::endl;
    }

    RemoveVectoredExceptionHandler(handler);
    std::cout << "end of main"<<std::endl;
    return 0;
}

The outputs of code are:

VectoredHandler
catch (...)
end of main

So,you can dump core int the function VectoredHandler . The VectoredHandler is called after the debugger gets a first chance notification, but before the system begins unwinding the stack. And if your purpose is just to debug the problem issue, then you can rely on the debugger feature to handle the first chance exception, don't need dump the application.

For your information, you may need know What is a First Chance Exception? in windows to understand how windows dispatch the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM