每当C++中出现异常时,它就按照使用TestCcatch块定义的行为来处理。然而,经常会出现这样的情况:异常被抛出,但没有被捕获,因为异常处理子系统无法为该特定异常找到匹配的捕获块。在这种情况下,会发生以下一组操作:
null
- 异常处理子系统调用以下函数: 意外的 此函数由默认C++库提供,定义了当未发生异常时的行为。默认情况下,意外呼叫 终止 .
- terminate函数定义了流程终止期间要执行的操作。默认情况下,这会调用 中止 .
- 该过程被中止。
terminate()和unexpected()只需调用其他函数来实际处理错误。如上所述,terminate调用abort()和意外()调用terminate()。因此,当发生异常处理错误时,这两个函数都会停止程序执行。但是,您可以更改终止发生的方式。
要更改终止处理程序,使用的函数设置为_terminate(terminate _handlernewhandler),该函数在标头中定义 .
以下程序演示如何设置自定义终止处理程序:
// CPP program to set a new termination handler // for uncaught exceptions. #include <exception> #include <iostream> using namespace std; // definition of custom termination function void myhandler() { cout << "Inside new terminate handler" ; abort (); } int main() { // set new terminate handler set_terminate(myhandler); try { cout << "Inside try block" ; throw 100; } catch ( char a) // won't catch an int exception { cout << "Inside catch block" ; } return 0; } |
输出:
Inside try block Inside new terminate handler
运行时错误:
Abort signal from abort(3) (SIGABRT)
需要注意的是,定制终止处理程序必须做的唯一一件事就是停止程序执行。不得以任何方式返回或恢复该程序。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END