Introduction

This article describes standard techniques of handling exceptions and errors in Visual C++ programs running in Windows.  

An exception (or a critical error, or crash) typically means your program stops working normally and needs to stop its execution. For example, an exception may occur because of your program accesses an invalid memory address (such as NULL pointer), memory buffer can't be allocated (out of memory), C run-time libraries (CRT) detect an error and request program termination and so on.  

A C++ program may handle several types of exceptions: SEH exceptions produced through operating system's structured exception handling mechanism, CRT errors produced by the C run-time libraries, and, finally, signals. Each error type requires installing an exception handler function that would intercept an exception and do some error recovery actions. 

If your application has several execution threads, things may be even more complicated. Some exception handlers work for entire process, but some work for the current thread only. So you have to install exception handlers in each thread. 

Each module (EXE or DLL) in your application is linked to CRT libraries (either statically or dynamically). Exception handling techiniques strongly depend on the CRT linkage type.  

The variety of error types, differences of handling exceptions in multi-threaded programs and dependence of exception handling on CRT linkage requires a lot of work to handle exactly all exceptions that your application is allowed to handle. This article is aimed to help you better understand the exception handling mechanisms and effectively use exception handling in your C++ applications. 

Background 

Some time ago I needed a way for intercepting exceptions for one of my open-source projects, CrashRpt - A crash reporting library for Windows applications. The CrashRpt library handles the exceptions occurring in your application, collects technical information about the error (such as crash minidump, error logs, desktop screenshots) and offers the user to send error report over the Internet (figure 1).    

Figure 1 - Error Report Window and Error Report Details dialogs of the CrashRpt library 

crashrpt.png

Maybe you have ever seen the Windows Error Reporting window (figure 2) suddenly appearing on your desktop, so the CrashRpt library does the same things, except it sends the error report to your own web-server instead of Microsoft's server.  

Figure 2 - Windows Error Reporting (Dr.Watson) window 

wer.gif

So, browsing the MSDN gave me the SetUnhandledExceptionFilter() function that I used to handle access violations. But soon I figured out that some of exceptions in my application are somehow left unhandled and Dr.Watson's window still appears instead of CrashRpt window. 

I browsed MSDN some more time and found many other CRT-provided functions that should be used to handle CRT errors. Here are some examples of such functions: set_terminate(), _set_invalid_parameter_handler(), _set_purecall_handler()

Then I found that some CRT handlers are valid for the current thread only, but some of them work for the all threads of the process.   

Continuing my research I found out that there are many nuances a developer must understand to use exception handling effectively. Results of my research are presented below.   

Some Words about Exceptions 

As you alredy know, an exception or a critical error typically means that a program stops working normally and needs to stop its execution.   

For example, an exception may occur because of the following: 

  • program accesses an invalid memory address (such as NULL pointer) 
  • stack is overflown due to infinite recursion 
  • large block of data is written to a small buffer
  • a pure virtual method of a C++ class is called 
  • memory buffer can't be allocated (out of memory)
  • invalid parameter is passed to a C++ system function
  • C run-time libraries detect an error and request program termination

There are two kinds of exceptions that have different nature: SEH exceptions (Structured Exception Handling, SEH) and typed C++ exceptions. You can find an in-depth description of exception mechanism implementation in the excellent How a C++ compiler implements exception handling article by Vishal Kochhar.   

Structured exception handling mechanism is provided by the operating system (this means exactly all Windows applications can raise and handle SEH exceptions). SEH exceptions were originally designed for C language, but they can be used in C++, too.  

SEH exceptions are handled using __try{}__except(){} construction. The main() function of your program is guarded with such construction, so by default all unhandled SEH exceptions are caught and Dr.Watson is invoked. SEH exceptions are Visual C++ compiler-specific. If you write portable code, you should guard the structured exception handling construction with #ifdef/#endif

Code example: 

  int* p = NULL;   // pointer to NULL
  __try
  {
    // Guarded code
    *p = 13; // causes an access violation exception
  }
  __except(EXCEPTION_EXECUTE_HANDLER) // Here is exception filter expression
  {  
    // Here is exception handler
 
    // Terminate program
    ExitProcess(1);
  }

In other hand, C++ typed exception mechanism is provided by the C run-time libraries (this means that only C++ applications can raise and handle such exceptions). C++ typed exceptions are handled using try{}catch{} construction. An example is presented below (the code taken from http://www.cplusplus.com/doc/tutorial/exceptions/):

// exceptions
#include <iostream>
using namespace std;
int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << endl;
  }
  return 0;
} 

Structured Exception Handling 

When a SEH exception occurs, you typically see a window of Dr.Watson (see figure 2) that offers to send error report to Microsoft. You even can generate a SEH exception yourself using RaiseException() function. 

Each SEH exception has an associated exception code. You can extract the exception code inside of __except statement using GetExceptionCode() intrinsic function. You can extract exception information inside of __except statement using GetExceptionInformation() intrinsic function. To use these intrinsic functions you usually create your custom exception filter as shown in the example below. 

The following example shows how to use a SEH exception filter.

int seh_filter(unsigned int code, struct _EXCEPTION_POINTERS* ep)
{
  // Generate error report
  // Execute exception handler
  return EXCEPTION_EXECUTE_HANDLER;
}
void main()
{
  __try
  {
    // .. some buggy code here
  }
  __except(seh_filter(GetExceptionCode(), GetExceptionInformation()))
  {    
    // Terminate program
    ExitProcess(1);
  }
}

The __try{}__except(){} construction is mostly C oriented. However, you can redirect a SEH exception to a C++ typed exception and handle it as you do with C++ typed exceptions. This can be done using the _set_se_translator() function provided by C++ runtime libraries (CRT).

Code example (taken from MSDN): 

// crt_settrans.cpp
// compile with: /EHa
#include <stdio.h>
#include <windows.h>
#include <eh.h>
void SEFunc();
void trans_func( unsigned int, EXCEPTION_POINTERS* );
class SE_Exception
{
private:
    unsigned int nSE;
public:
    SE_Exception() {}
    SE_Exception( unsigned int n ) : nSE( n ) {}
    ~SE_Exception() {}
    unsigned int getSeNumber() { return nSE; }
};
int main( void )
{
    try
    {
        _set_se_translator( trans_func );
        SEFunc();
    }
    catch( SE_Exception e )
    {
        printf( "Caught a __try exception with SE_Exception.\n" );
    }
}
void SEFunc()
{
    __try
    {
        int x, y=0;
        x = 5 / y;
    }
    __finally
    {
        printf( "In finally\n" );
    }
}
void trans_func( unsigned int u, EXCEPTION_POINTERS* pExp )
{
    printf( "In trans_func.\n" );
    throw SE_Exception();
} 

However, the disadvantage of the __try{}__catch(Expression){} construction is that you may forget to guard a potentially incorrect code that may cause an exception that won't be handled by your program. Such an unhandled SEH exception can be caught using the top-level unhandled exception filter set with the SetUnhandledExceptionFilter() function.

Note: The word top-level means that if someone calls the SetUnhandledExceptionFilter() function after your call, the exception filter will be replaced. This is the disadvantage, because you can't chain top-level handlers one above another. Such a disadvantage can be eliminated by Vectored Exception Handling mechanism discussed later. 

The exception information (CPU state before the exception occurred) is passed to the exception handler through EXCEPTION_POINTERS structure.

Code example: 

LONG WINAPI MyUnhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionPtrs)
{
  // Do something, for example generate error report
  //..
  // Execute default exception handler next
  return EXCEPTION_EXECUTE_HANDLER; 
} 
void main()
{ 
  SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);
  // .. some unsafe code here 
} 

The top-level SEH exception handler works for all threads of the caller process, so its enough to call it once in the beginning of your main() function.

The top-level SEH exception handler is called in context of the thread where exception have occurred. This can affect the exception handler's ability to recover from certain exceptions, such as an invalid stack. 

If your exception handler function is located inside of a DLL, you should be careful when using the SetUnhandledExceptionFilter() function. If your DLL is unloaded at the moment of crash, the behavior may be unpredictable.

Note: In Windows 7, there is a new function - RaiseFailFastException(). This function allows to ignore all installed exception handlers (either SEH or vectored) and pass the exception directly to Dr.Watson. Typically, you call this function if your application is in a bad state and you want to terminate the application immediately and have a Windows Error Report created. For additional information, see the Reference section below. 

Vectored Exception Handling 

Vectored exception handling (VEH) is an extension to structured exception handling. It was introduced in Windows XP.

To add a vectored exception handler, you can use the AddVectoredExceptionHandler() function. The disadvantage is that VEH is available in Windows XP and later, so the presence of AddVectoredExceptionHandler() function should be checked at run-time.

To remove the previously installed handler, use the RemoveVectoredExceptionHandler() function. 

VEH allows to watch or handle all SEH exceptions for the application. To preserve backward compatibility, when a SEH exception occurs in some part of the program, the system calls installed VEH handlers in turn, after that it searches for the usual SEH handlers.

An advantage of VEH is an ability to chain exception handlers, so if somebody installs vectored exception handler above yours, you still can intercept the exception.

Vectored exception handling is suitable when you need to monitor _ALL_ SEH exceptions, like a debugger does. But the problem is you have to decide which exception to handle and which to skip. In program's code, some exceptions may be intentionally guarded by __try{}__except(){} construction, and handling such exceptions in VEH and not passing it to frame-based SEH handler, you may introduce bugs into application logics.

I think that the SetUnhandledExceptionFilter() function is more suitable for exception handling than VEH, because it is the top-level SEH handler. If nobody handles the exception, top-level SEH handler is called and you don't need to decide if you should skip the exception or not. 

CRT Error Handling 

In addition to SEH exceptions and C++ typed exceptions, C runtime libraries (CRT) provide their own error handling mechanism that should be taken into account in your program. When a CRT error occurs, you typically see a CRT error message window (figure 3).

Figure 3 - CRT Error Message 

invparam_error.png 

Terminate Handler 

When CRT encounters an unhandled C++ typed exception, it calls terminate() function. To intercept such calls and take an appropriate action you should set error handler using set_terminate() function.

Code example: 

void my_terminate_handler()
{
  // Abnormal program termination (terminate() function was called)
  // Do something here
  // Finally, terminate program
  exit(1); 
}
void main()
{
  set_terminate(my_terminate_handler);
  terminate();
} 

There is unexpected() function that is not used with the current implementation of Visual C++ exception handling. However, consider using the set_unexpected() function to set handler for the unexpected() function, too.

Note: In a multi-threaded environment, unexpected and terminate functions are maintained separately for each thread. Each new thread needs to install its own unexpected and terminate function. Thus, each thread is in charge of its own unexpected and terminate handling.

Pure Call Handler 

Use the _set_purecall_handler() function to handle pure virtual function calls. This function can be used in VC++ .NET 2003 and later. This function works for all threads of the caller process.

Code example (taken from MSDN):

// _set_purecall_handler.cpp
// compile with: /W1
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
class CDerived;
class CBase
{
public:
   CBase(CDerived *derived): m_pDerived(derived) {};
   ~CBase();
   virtual void function(void) = 0;
   CDerived * m_pDerived;
};
class CDerived : public CBase
{
public:
   CDerived() : CBase(this) {};   // C4355
   virtual void function(void) {};
};
CBase::~CBase()
{
   m_pDerived -> function();
}
void myPurecallHandler(void)
{
   printf("In _purecall_handler.");
   exit(0);
}
int _tmain(int argc, _TCHAR* argv[])
{
   _set_purecall_handler(myPurecallHandler);
   CDerived myDerived;
} 

New Operator Fault Handler 

Use the _set_new_handler() function to handle memory allocation faults. This function can be used in VC++ .NET 2003 and later. This function works for all threads of the caller process. Consider also using the _set_new_mode() function to define error behaviour for the malloc() function. 

Code example (taken from MSDN): 

#include <new.h>
int handle_program_memory_depletion( size_t )
{
   // Your code
}
int main( void )
{
   _set_new_handler( handle_program_memory_depletion );
   int *pi = new int[BIG_NUMBER];
} 

Invalid Parameter Handler 

Use the _set_invalid_parameter_handler() function to handle situations when CRT detects an invalid argument in a system function call. This function can be used in VC++ 2005 and later. This function works for all threads of the caller process.

Code example (taken from MSDN):

// crt_set_invalid_parameter_handler.c
// compile with: /Zi /MTd
#include <stdio.h>
#include <stdlib.h>
#include <crtdbg.h>  // For _CrtSetReportMode
void myInvalidParameterHandler(const wchar_t* expression,
   const wchar_t* function, 
   const wchar_t* file, 
   unsigned int line, 
   uintptr_t pReserved)
{
   wprintf(L"Invalid parameter detected in function %s."
            L" File: %s Line: %d\n", function, file, line);
   wprintf(L"Expression: %s\n", expression);
}
int main( )
{
   char* formatString;
   _invalid_parameter_handler oldHandler, newHandler;
   newHandler = myInvalidParameterHandler;
   oldHandler = _set_invalid_parameter_handler(newHandler);
   // Disable the message box for assertions.
   _CrtSetReportMode(_CRT_ASSERT, 0);
   // Call printf_s with invalid parameters.
   formatString = NULL;
   printf(formatString);
} 

C++ Signal Handling 

C++ provides program interruption mechanism called signals. You can handle signals with the signal() function. 

In Visual C++, there are 6 types of signals: 

  • SIGABRT Abnormal termination 
  • SIGFPE Floating-point error 
  • SIGILL Illegal instruction
  • SIGINT CTRL+C signal 
  • SIGSEGV Illegal storage access
  • SIGTERM Termination request

MSDN says that the SIGILL, SIGSEGV, and SIGTERM signals are not generated under Windows and included for ANSI compatiblity. However, practice shows that if you set the SIGSEGV signal handler in the main thread, it is called by CRT instead of SEH exception handler set with SetUnhandledExceptionFilter() function and the global variable _pxcptinfoptrs contains a pointer to the exception information. In other threads the exception filter set with SetUnhandledExceptionFilter() function is called instead of SIGSEGV handler. 

Note: In Linux, signals are the main way of exception handling (Linux's implementation of C run-time, glibc, also provides set_unexpected() and set_terminate() handlers). As you can see, in Windows signals are not used as intensively as they deserve. Instead of using signals, C run-time libraries provide several Visual C++-specific error handler functions, such as _invalid_parameter_handler() and so on. 

The _pxcptinfoptrs global variable can be also used in the SIGFPE handler. In all other signal handlers it seems to be NULL

The SIGFPE signal handler is called by CRT when a floating point error occurs, such as division by zero. However, by default floating point exceptions are not generated, instead NaN or infinity numbers are generated as the result of a floating point operation. Use the _controlfp_s() function to enable the floating point exception generation.

You can generate all 6 signals manually using raise() function.

Example: 

void sigabrt_handler(int)
{
  // Caught SIGABRT C++ signal
  // Terminate program
  exit(1);
}
void main()
{
  signal(SIGABRT, sigabrt_handler);
     
  // Cause abort
  abort();       
}                

Note: Although it is not well documented in MSDN, it seems that you should install SIGFPE, SIGILL and SIGSEGV signal handlers for each new thread in your program. The SIGABRT, SIGINT and SIGTERM signal handlers seems to work for all threads of the caller process, so you should install them once in your main() function.

Retrieving Exception Information 

When an exception occurs you typically want to get the CPU state to determine the place in your code that caused the problem. You may want to pass this information to the MiniDumpWriteDump() function to debug the problem later (for example of how to do this, see the XCrashReport : Exception Handling and Crash Reporting - Part 3 article by Hans Dietrich). The way you retrieve the exception information differs depending on the exception handler you use. 

In the SEH exception handler set with the SetUnhandledExceptionFilter() function, the exception information is retrieved from EXCEPTION_POINTERS structure passed as function parameter. 

In __try{}__catch(Expression){} construction you retrieve exception information using GetExceptionInformation() intrinsic function and pass it to the SEH exception filter function as parameter.

In the SIGFPE and SIGSEGV signal handlers you can retrieve the exception information from the _pxcptinfoptrs global CRT variable that is declared in <signal.h>. This variable is not documented well in MSDN.

In other signal handlers and in CRT error handlers you have no ability to easily extract the exception information. I found a workaround used in CRT code (see CRT 8.0 source files, invarg.c, line 104).

The following code shows how to get current CPU state used as exception information.

#if _MSC_VER>=1300
#include <rtcapi.h>
#endif
#ifndef _AddressOfReturnAddress
// Taken from: http://msdn.microsoft.com/en-us/library/s975zw7k(VS.71).aspx
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
// _ReturnAddress and _AddressOfReturnAddress should be prototyped before use 
EXTERNC void * _AddressOfReturnAddress(void);
EXTERNC void * _ReturnAddress(void);
#endif 
// The following function retrieves exception info
void GetExceptionPointers(DWORD dwExceptionCode, 
  EXCEPTION_POINTERS** ppExceptionPointers)
{
  // The following code was taken from VC++ 8.0 CRT (invarg.c: line 104)
  
  EXCEPTION_RECORD ExceptionRecord;
  CONTEXT ContextRecord;
  memset(&ContextRecord, 0, sizeof(CONTEXT));
  
#ifdef _X86_
  __asm {
      mov dword ptr [ContextRecord.Eax], eax
      mov dword ptr [ContextRecord.Ecx], ecx
      mov dword ptr [ContextRecord.Edx], edx
      mov dword ptr [ContextRecord.Ebx], ebx
      mov dword ptr [ContextRecord.Esi], esi
      mov dword ptr [ContextRecord.Edi], edi
      mov word ptr [ContextRecord.SegSs], ss
      mov word ptr [ContextRecord.SegCs], cs
      mov word ptr [ContextRecord.SegDs], ds
      mov word ptr [ContextRecord.SegEs], es
      mov word ptr [ContextRecord.SegFs], fs
      mov word ptr [ContextRecord.SegGs], gs
      pushfd
      pop [ContextRecord.EFlags]
  }
  ContextRecord.ContextFlags = CONTEXT_CONTROL;
#pragma warning(push)
#pragma warning(disable:4311)
  ContextRecord.Eip = (ULONG)_ReturnAddress();
  ContextRecord.Esp = (ULONG)_AddressOfReturnAddress();
#pragma warning(pop)
  ContextRecord.Ebp = *((ULONG *)_AddressOfReturnAddress()-1);
#elif defined (_IA64_) || defined (_AMD64_)
  /* Need to fill up the Context in IA64 and AMD64. */
  RtlCaptureContext(&ContextRecord);
#else  /* defined (_IA64_) || defined (_AMD64_) */
  ZeroMemory(&ContextRecord, sizeof(ContextRecord));
#endif  /* defined (_IA64_) || defined (_AMD64_) */
  ZeroMemory(&ExceptionRecord, sizeof(EXCEPTION_RECORD));
  ExceptionRecord.ExceptionCode = dwExceptionCode;
  ExceptionRecord.ExceptionAddress = _ReturnAddress();
  
  EXCEPTION_RECORD* pExceptionRecord = new EXCEPTION_RECORD;
  memcpy(pExceptionRecord, &ExceptionRecord, sizeof(EXCEPTION_RECORD));
  CONTEXT* pContextRecord = new CONTEXT;
  memcpy(pContextRecord, &ContextRecord, sizeof(CONTEXT));
  *ppExceptionPointers = new EXCEPTION_POINTERS;
  (*ppExceptionPointers)->ExceptionRecord = pExceptionRecord;
  (*ppExceptionPointers)->ContextRecord = pContextRecord;  
}

Exception Handling and CRT Linkage

Each module (EXE, DLL) in your application is linked to CRT (C run-time libraries). You may link CRT as multi-threaded static library or as multi-threaded dynamic link library. When you set CRT error handlers, such as terminate handler, unexpected handler, pure call handler, invalid parameter handler, new operator error handler or a signal handler, they will work for the CRT the caller module is linked to and won't intercept exceptions in different CRT modules (if exist), because each CRT module has its own internal state. 

Several project modules may share single CRT DLL. This reduces to minimum the overall size of linked CRT code. And all exceptions within that CRT DLL can be handled at once. That's why multi-threaded CRT DLL is the recommended way of CRT linkage. However, many developers still prefer static CRT linkage because it's easier to distribute a single executable module statically linked with CRT than to distribute the same executable linked with several dynamic-link CRT libraries (for more information, see the Create projects easily with private MFC, ATL and CRT assemblies article by Martin Richter). 

If you plan to use CRT as a static link library (which is not recommended to do) and want to use some exception handling functionality, you have to build the functionality as a static library with /NODEFAULTLIB linker flag and then link this functionality to each EXE and DLL module of your application. You would also have to install the CRT error handlers for each module of your application, while the SEH exception handler would still be installed once. 

Visual C++ Compiler Flags

There are several Visual C++ compiler switches that are related to exception handling. You can find the switches if open project Properties->Configuration Properties->C/C++->Code Generation

Exception Handling Model 

You can set an exception handling model for your Visual C++ compiler with /EHs (or EHsc) to specify synchronous exception handling model or /EHa to specify asynchronous exception handling model. The asynchronous model can be used to force the try{}catch(){} construction to catch both SEH and C++ typed exceptions (the same effect can be achieved with the _set_se_translator() function). If synchronous model is utilized, SEH exceptions are not cought by the try{}catch(){} construction. Asynchronous model was default in previous versions of Visual C++, but synchronous one is default in the newer versions. 

Floating Point Exceptions 

You can enable floating point exceptions using /fp:except compiler flag. This option is disabled by default, so floating point exceptions are not raised. For more information, see the /fp (Specify Floating Point Behavior) in the Reference section below. 

Buffer Security Checks 

By default, you have the /GS (Buffer Security Check) compiler flag enabled that forces compiler to inject code that would check buffer overruns. A buffer overrun is a situation when a large block of data is written to a small buffer.  

Note: In Visual C++ .NET (CRT 7.1) you can use _set_security_error_handler() function that CRT calls when buffer overrun is detected. However, this function is deprecated in the later versions of CRT. 

Since CRT 8.0 you can't intercept buffer overrun errors in your code. When buffer overrun is detected, CRT invokes Dr.Watson directly instead of calling unhandled exception filter. This is done because of security reasons and Microsoft doesn't plan to change this behavior.  For additional info please see these links:  

Reference 

History   

  • 7 June 2011 - Initial release.
  • 10 June 2011 - Added Visual C++ Compiler Flags and Reference section 

 

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"