Home Backend Development C#.Net Tutorial Exception handling skills for C++ programs

Exception handling skills for C++ programs

Dec 16, 2016 am 09:42 AM

Handling exceptions in C++ comes with a few implicit limitations at the language level, but in some cases you can get around them. By learning various ways to exploit exceptions, you can produce more reliable applications. Preserving exception source information In C++, whenever an exception is caught within a handler, information about the exception source is unknown. The specific source of the 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, you can generate a stack trace in the exception object's constructor during the throw statement. ExceptionTracer is a class that demonstrates this behavior. Listing 1. Generating a stack trace in the exception object constructor // Sample PRogram:

// Compiler: gcc 3.2.3 20030502

// linux: Red Hat #include

#include < ;signal.h> #include

#include 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);

}

}; Governance Signals Whenever a process performs a nasty action that causes the Linux? kernel to emit a signal, the signal must be processed. Signal handlers usually release some important resources and terminate the application. In this case, all object instances on the stack are in an undestructed state. On the other hand, if these signals are converted into C++ exceptions, then you can call their constructors gracefully and arrange multiple layers of catch blocks to better handle these signals. The SignalExceptionClass, defined in Listing 2, provides an abstraction for representing C++ exceptions that may be signaled by the kernel. SignalTranslator is a template class based on SignalExceptionClass, which is usually used to implement conversion to C++ exceptions. At any instant, only one signal handler can handle a signal for an active process. Therefore, SignalTranslator adopts the singleton design pattern. The overall concept is demonstrated through the SegmentationFault class for SIGSEGV and the FloatingPointException class for SIGFPE. Listing 2. Convert signals into 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 return SIGFPE;}

} ; SignalTranslator

g_objFloatingPointExceptionTranslator; Managing exceptions in constructors and destructors It is impossible for every ANSI C++ to catch exceptions during the construction and destruction of global (static global) variables. Therefore, ANSI C++ does not recommend throwing exceptions in the constructors and destructors of classes whose instances may be defined as global instances (static global instances). In other words, never define global (static global) instances for classes whose constructors and destructors may throw exceptions. However, assuming a specific compiler and a specific system, it might be possible to do so, and fortunately, this is exactly the case with GCC on Linux. This can be demonstrated using the ExceptionHandler class, which also adopts the singleton design pattern. Its constructor registers an uncaught handler. Because only one uncaught handler can handle an active process at a time, the constructor should be called only once, hence the singleton pattern. The global (static global) instance of ExceptionHandler should be defined before the actual global (static global) variable in question is defined. Listing 3. Handling exceptions in constructors class ExceptionHandler


{

private:

class SingleTonHandler

{

public:

SingleTonHandler()

{

set_terminate(Handler);

} static void Handler()

{

// Exception from constrUCtion/destruction of global  variables try

{

// re-throw throw;

}

catch (SegmentationFault &)

{

cout << “SegmentationFault” << endl;

}

catch (FloatingPointException &)

{

cout << “FloatingPointException” << endl;

}

catch (...)

{

cout << “Unknown Exception” << endl;

} //if this is a thread performing some core activity

abort();

// else if this is a thread used to service requests

// pthread_exit();

}

}; public:

ExceptionHandler()

{

static SingleTonHandler s_objHandler;

}

}; ////////////////////////////////////////////////////////////////////////// class A

{

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::SingleTonHandler() is 

invoked

ExceptionHandler g_objExceptionHandler;

A g_a; ////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[])

{

return 0;

}     处理多线程程序中的异常 有时一些异常没有被捕捉,这将造成进程异常中止。不过很多时候,进程包含多个线程,其中少数线程执行核心应用程序逻辑,同时,其余线程为外部请求提供服务。假如服务线程因编程错误而没有处理某个异常,则会造成整个应用程序崩溃。这一点可能是不受人们欢迎的,因为它会通过向应用程序传送不合法的请求而助长拒绝服务攻击。为了避免这一点,未捕捉处理程序可以决定是请求异常中止调用,还是请求线程退出调用。清单3 中 ExceptionHandler::SingleTonHandler::Handler() 函数的末尾处展示了该处理程序。 结束语 我简单地讨论了少许 C++ 编程设计模式,以便更好地执行以下任务: ·在抛出异常的时候追踪异常的来源。

·将信号从内核程序转换成 C++ 异常。

·捕捉构造和/或析构全局变量期间抛出的异常。

·多线程进程中的异常处理。

以上就是C++程序的异常处理技巧的内容,更多相关文章请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ function exceptions and multithreading: error handling in concurrent environments C++ function exceptions and multithreading: error handling in concurrent environments May 04, 2024 pm 04:42 PM

Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

How does C++ exception handling support custom error handling routines? How does C++ exception handling support custom error handling routines? Jun 05, 2024 pm 12:13 PM

C++ exception handling allows the creation of custom error handling routines to handle runtime errors by throwing exceptions and catching them using try-catch blocks. 1. Create a custom exception class derived from the exception class and override the what() method; 2. Use the throw keyword to throw an exception; 3. Use the try-catch block to catch exceptions and specify the exception types that can be handled.

What is the relationship between recursive calls and exception handling in Java functions? What is the relationship between recursive calls and exception handling in Java functions? May 03, 2024 pm 06:12 PM

Exception handling in recursive calls: Limiting recursion depth: Preventing stack overflow. Use exception handling: Use try-catch statements to handle exceptions. Tail recursion optimization: avoid stack overflow.

Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? May 09, 2024 pm 12:36 PM

In multithreaded C++, exception handling follows the following principles: timeliness, thread safety, and clarity. In practice, you can ensure thread safety of exception handling code by using mutex or atomic variables. Additionally, consider reentrancy, performance, and testing of your exception handling code to ensure it runs safely and efficiently in a multi-threaded environment.

How to handle exceptions in C++ Lambda expressions? How to handle exceptions in C++ Lambda expressions? Jun 03, 2024 pm 03:01 PM

Exception handling in C++ Lambda expressions does not have its own scope, and exceptions are not caught by default. To catch exceptions, you can use Lambda expression catching syntax, which allows a Lambda expression to capture a variable within its definition scope, allowing exception handling in a try-catch block.

PHP exception handling: understand system behavior through exception tracking PHP exception handling: understand system behavior through exception tracking Jun 05, 2024 pm 07:57 PM

PHP exception handling: Understanding system behavior through exception tracking Exceptions are the mechanism used by PHP to handle errors, and exceptions are handled by exception handlers. The exception class Exception represents general exceptions, while the Throwable class represents all exceptions. Use the throw keyword to throw exceptions and use try...catch statements to define exception handlers. In practical cases, exception handling is used to capture and handle DivisionByZeroError that may be thrown by the calculate() function to ensure that the application can fail gracefully when an error occurs.

How to profile a C++ program to identify performance bottlenecks? How to profile a C++ program to identify performance bottlenecks? May 08, 2024 am 11:33 AM

By using analysis tools such as Valgrind, gprof or perf and optimizing function signatures, data structures and memory allocation, you can identify and eliminate performance bottlenecks in C++ programs and improve application efficiency. For example, if a function that computes an equation is bottlenecked by using an inefficient data structure, replacing it with a hash table and employing object pooling can significantly improve performance. Continuous monitoring and benchmarking help ensure performance remains optimal over time.

How to handle cross-thread C++ exceptions? How to handle cross-thread C++ exceptions? Jun 06, 2024 am 10:44 AM

In multi-threaded C++, exception handling is implemented through the std::promise and std::future mechanisms: use the promise object to record the exception in the thread that throws the exception. Use a future object to check for exceptions in the thread that receives the exception. Practical cases show how to use promises and futures to catch and handle exceptions in different threads.

See all articles