如果异常不在函数中引发,那么异常必须被捕获。如果没有没有被捕获,则异常称为未捕获异常。默认情况下,系统会调用termiate终止程序。
系统默认terminate函数会调用abort()函数终止程序。我们可以改变terminate函数的行为。使用set_terminate();
typedef void (*terminate_function)();
terminate_function set_terminate( terminate_function term_func );
下面是实例程序:
#include <exception>
#include <iostream>
#include <cstdlib>
#include <stdexcept>
using namespace std;
void myQuit()
{
cout << "Terminating test because of uncaught exception" << endl;
exit(5);
}
int main()
{
terminate_handler oldHandler = set_terminate(myQuit);
int switch_K = 1;
logic_error a("Exception: logic_error");
range_error b("Exception: runtime_error");
while(switch_K)
{
try
{
cin >> switch_K ;
switch(switch_K)
{
case 1:
throw a;
break;
default:
cout << "throw a runtime_error" << endl;
throw b;
break;
}
}
catch(const logic_error & e)
{
cout << e.what() << endl;
}
catch(...)
{
cout << "OK" << endl;
terminate();
}
}
return 0;
}
在Shell中运行该程序: