Exception Handling Techniques for C ++ programs in Linux

Source: Internet
Author: User
Exception Handling Skills for C ++ programs in Linux-general Linux technology-Linux programming and kernel information. For details, refer to the following section. Exception Handling Techniques for C ++ programs in Linux
Baidu

Exceptions in C ++ may encounter some Implicit restrictions at the language level, but in some cases, you can bypass them. By learning a variety of ways to use exceptions, you can produce more reliable applications.

Retain exception source information

In C ++, whenever an exception is captured in the handler, information about the exception source is unknown. The specific source of an exception can provide a lot of important information to better handle the exception, or provide some information that can be appended to the error log for later analysis.

To solve this problem, a stack trace can be generated in the constructor of the exception object during the exception statement throw. Predictiontracer is a class that demonstrates such behavior.

Listing 1. Generate a stack trace in the exception object constructor

// Sample Program:
// Compiler: gcc 3.2.3 20030502
// Linux: Red Hat

# Include
# Include

# Include
# Include

Using namespace std;

//////////////////////////////////////// /////

Class ExceptionTracer
{
Public:
Predictiontracer ()
{
Void * array [25];
Int nSize = backtrace (array, 25 );
Char ** symbols = backtrace_symbols (array, nSize );
 
For (int I = 0; I <nSize; I ++)
{
Cout <symbols <Endl;
}

Free (symbols );
}
};

Manage Signals

Every time a process executes an annoying action, so that Linux? When the kernel sends a signal, the signal must be processed. Signal processing programs usually release some important resources and terminate applications. In this case, all the object instances on the stack are in the undamaged state. On the other hand, if these signals are converted to C ++ exceptions, You can elegantly call their constructor and arrange multi-layer catch blocks to better process these signals.

The SignalExceptionClass defined in Listing 2 provides an abstraction of the C ++ exception that represents a possible signal from the kernel. SignalTranslator is a template class based on SignalExceptionClass, which is usually used to implement conversion to C ++ exceptions. At any moment, only one signal processing program can process one signal of an active process. Therefore, SignalTranslator adopts the singleton design mode. The overall concept is presented through the SegmentationFault class for sigsegv and the FloatingPointException class for SIGFPE.

Listing 2. Converting signals to exceptions
  
Template Class SignalTranslator
{
Private:
Class SingleTonTranslator
{
Public:
SingleTonTranslator ()
{
Signal (SignalExceptionClass: GetSignalNumber (),
SignalHandler );
}

Static void SignalHandler (int)
{
Throw SignalExceptionClass ();
}
};

Public:
SignalTranslator ()
{
Static SingleTonTranslator s_objTranslator;
}
};

// An example for SIGSEGV
Class SegmentationFault: public ExceptionTracer, public
Exception
{
Public:
Static int GetSignalNumber () {return SIGSEGV ;}
};

SignalTranslator
G_objSegmentationFaultTranslator;

// An example for SIGFPE
Class FloatingPointException: public ExceptionTracer, public
Exception
{
Public:
Static int GetSignalNumber () {return SIGFPE ;}
};

SignalTranslator
G_objFloatingPointExceptionTranslator;

Manage constructor and destructor exceptions

During the construction and Analysis of Global (static global) variables, it is impossible for every ansi c ++ to catch exceptions. Therefore, ansi c ++ does not recommend that you throw an exception in constructor and destructor of classes whose instances may be defined as global instances (static global instances. In other words, we should never define global (static global) Instances for classes whose constructors and destructor may throw exceptions. However, if we assume there is a specific compiler and a specific system, we may be able to do this. Fortunately, this happens to GCC on Linux.

You can use the ExceptionHandler class to demonstrate this. This class also adopts the singleton design mode. Its constructor registers an uncaptured handler. Because only one uncaptured handler can process one active process at a time, the constructor should be called only once, so the singleton mode should be used. You should define the global (static global) instance of predictionhandler before defining the problematic global (static global) variable.

Listing 3. Handling exceptions in Constructor

Class ExceptionHandler
{
Private:
Class SingleTonHandler
{
Public:
SingleTonHandler ()
{
Set_terminate (Handler );
}

Static void Handler ()
{
// Exception from construction/destruction of global variables try
{
// Re-throw;
}
Catch (SegmentationFault &)
{
Cout <"SegmentationFault" <endl;
}
Catch (FloatingPointException &)
{
Cout <"FloatingPointException" <endl;
}
Catch (...)
{
Cout <"Unknown Exception" <endl;
}

// If this is a thread refreshing some core activity
Abort ();
// Else if this is a thread used to service requests
// Pthread_exit ();
}
};

Public:
ExceptionHandler ()
{
Static SingleTonHandler s_objHandler;
}
};

//////////////////////////////////////// //////////////////////////////////

Class
{
Public:
A ()
{
// Int I = 0, j = 1/I;
* (Int *) 0 = 0;
}
};

// Before defining any global variable, we define a dummy instance
// Of ExceptionHandler object to make sure that
// ExceptionHandler: SingleTonHandler () is
Invoked
ExceptionHandler g_objExceptionHandler;
A g_a;

//////////////////////////////////////// //////////////////////////////////

Int main (int argc, char * argv [])
{
Return 0;
}

Handle exceptions in multi-threaded programs

Sometimes some exceptions are not caught, which will cause the process to stop. However, in many cases, a process contains multiple threads, a few of which execute the core application logic. At the same time, other threads provide services for external requests. If the service thread does not handle an exception due to a programming error, the entire application will crash. This may be undesirable because it promotes denial-of-service attacks by sending illegal requests to applications. To avoid this, the uncaptured handler can decide whether the call is aborted due to an exception in the request or whether the request thread exits the call. In listing 3, the Handler is displayed at the end of the ExceptionHandler: SingleTonHandler: Handler () function.

Conclusion

I briefly discussed a few C ++ programming design patterns to better execute the following tasks:

· Track the source of the exception when an exception is thrown.
· An exception occurred while converting the signal from the kernel program to C ++.
· Capture exceptions thrown during constructor and/or destructor global variables.
· Exception Handling in multi-threaded processes.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.