First Chance exception handling ! RRS feed

  • Question

  • Hi -

                    I was going through the msdn tutorial of "Registering a Control Handler". When I execute the code given (http://msdn.microsoft.com/en-us/library/ms685049(v=vs.85).aspx) and give the Ctrl+c input, I am getting a first chance exception.  C++ try/catch mechanism isn't handling the situation. This is an system level exception ( i.e., interrupt ) and so how am I supposed to handle it ?

    Code :

    #include <windows.h>
    #include <stdio.h>

    BOOL CtrlHandler( DWORD fdwCtrlType )
      switch( fdwCtrlType )
        // Handle the CTRL-C signal.
        case CTRL_C_EVENT:
          printf( "Ctrl-C event\n\n" );
          Beep( 750, 300 );
          return( TRUE );

        // CTRL-CLOSE: confirm that the user wants to exit.
        case CTRL_CLOSE_EVENT:
          Beep( 600, 200 );
          printf( "Ctrl-Close event\n\n" );
          return( TRUE );

        // Pass other signals to the next handler.
        case CTRL_BREAK_EVENT:
          Beep( 900, 200 );
          printf( "Ctrl-Break event\n\n" );
          return FALSE;

        case CTRL_LOGOFF_EVENT:
          Beep( 1000, 200 );
          printf( "Ctrl-Logoff event\n\n" );
          return FALSE;

          Beep( 750, 500 );
          printf( "Ctrl-Shutdown event\n\n" );
          return FALSE;

          return FALSE;

    int main( void )
      if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) )
        printf( "\nThe Control Handler is installed.\n" );
        printf( "\n -- Now try pressing Ctrl+C or Ctrl+Break, or" );
        printf( "\n    try logging off or closing the console...\n" );
        printf( "\n(...waiting in a loop for events...)\n\n" );

        while( 1 ){ }
        printf( "\nERROR: Could not set control handler");
        return 1;
    return 0;

    Wednesday, January 18, 2012 4:13 PM


  • According to this MSDN article: http://msdn.microsoft.com/en-us/library/ms686016(v=vs.85).aspx

    "If a console process is being debugged and CTRL+C signals have not been disabled, the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger, and an application should never use an exception handler to deal with it. If the debugger handles the exception, an application will not notice the CTRL+C, with one exception: alertable waits will terminate. If the debugger passes the exception on unhandled, CTRL+C is passed to the console process and treated as a signal, as previously discussed." (emphasis is mine).

    "First-chance exception at 0x760dd3b1 in test.exe: 0x40010005: Control-C" that you get is exactly this case (see http://msdn.microsoft.com/en-us/library/cc704588(v=PROT.10).aspx)

    • Edited by Sergey Chepurin Wednesday, January 18, 2012 5:50 PM
    • Marked as answer by Rob Pan Monday, February 6, 2012 9:05 AM
    Wednesday, January 18, 2012 5:49 PM