Exception handling techniques for C + + programs under Linux

Source: Internet
Author: User

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);
 }
};

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.