1

See the code below. I run the code in windows 10, visual studio platform. The throw 1 can be caught in debug mode, but the throw failed in release mode with an error message "Unhandled exception at 0x00007FFC76DAA859: Microsoft C++ exception: int at memory location 0x000000D6464FF730". Any suggestions or comments are appreciated!

void MySignalHandler(int sig) {
    if (sig == SIGILL) {
        throw 1;
    }
    else {
        std::cerr << "Unknown signal code received.\n";
    }
}

int main() {
    signal(SIGILL, MySignalHandler); // install SIGILL handler
    int result = 1;
    try {
        raise(SIGILL);
    }
    catch (int i) {
        result = 0;
    }
    return result;
}
Charlie
  • 33
  • 5
  • 1
    Signals are handled in a separate context from the normal program flow. There are also commonly quite a lot of restrictions in signal handlers, like it can't use all kinds of system functions (especially I/O is usually severely restricted). But in this case, since it's running in another context from the rest of the program (think of it like it's running a separate thread) any exceptions you throw will be in that context only not in the context of the main program. – Some programmer dude May 12 '20 at 18:36
  • 2
    Since C++17 is it undefined behavior to throw an exception in a signal handler: https://en.cppreference.com/w/cpp/utility/program/signal#Signal_handler – NathanOliver May 12 '20 at 18:45
  • https://stackoverflow.com/questions/1717991/throwing-an-exception-from-within-a-signal-handler – Wör Du Schnaffzig May 12 '20 at 22:15
  • @Someprogrammerdude Thank you for your reply. This addressed part of my question. If the signal is handled in a separate context, why the "throw" works and can be caught in debug mode rather than release mode? Is there any difference between release and debug mode in terms of signal handling? – Charlie May 14 '20 at 21:03
  • That really could be something do do with just how debug builds are created, or how the debugger itself handles signals. – Some programmer dude May 14 '20 at 21:07
  • It might just be a question of timing. But anyway, the message is that you're not allowed to do it. – TonyK May 14 '20 at 21:34

0 Answers0