Handling Exceptions in C + + can encounter a little implicit restriction at the language level, but in some cases you can bypass them. Learn a variety of ways to exploit exceptions, and you can produce more reliable applications.
Keep Exception Source information
In C + +, information about the source of the exception is unknown whenever an exception is caught in the handler. The specific source of the exception can provide many important information to better handle the exception, or provide some information that can be attached to the error log for later analysis.
To solve this problem, you can generate a stack trace in the constructor of an exception object during the throw of an exception statement. Exceptiontracer is a class that demonstrates this behavior.
Listing 1. To generate a stack trace in an exception object constructor
// Sample Program:
// Compiler: gcc 3.2.3 20030502
// Linux: Red Hat
#include <execinfo.h>
#include <signal.h>
#include <exception>
#include <iostream>
using namespace std;
/////////////////////////////////////////////
class ExceptionTracer
{
public:
ExceptionTracer()
{
void * array[25];
int nSize = backtrace(array, 25);
char ** symbols = backtrace_symbols(array, nSize);
for (int i = 0; i < nSize; i++)
{
cout << symbols[i] << endl;
}
free(symbols);
}
};