读书人

有关C++ 错误处理的两个有关问题

发布时间: 2012-03-17 19:06:28 作者: rapoo

有关C++ 异常处理的两个问题
//set_new_handler处理new故障
#include <iostream>
#include <new>
#include <cstdlib>

using namespace std;

void customNewHandler()
{
cerr<<"customNewHandler was called";
abort();
}

int main()
{
double *ptr[50];
set_new_handler(customNewHandler);//依然调用了terminate函数而不是正常退出,为什么呢?

for(int i = 0;i<50;i++)
{
ptr[i] = new double[50000000];
cout<<"Allocated 50000000 doubles in ptr["<<i<<"]\n";
}

return 0;
}

//栈展开
#include <iostream>
#include <stdexcept>
using namespace std;

void function3()throw(runtime_error)// 函数定义后面为什么要加上throw(runtime_error)???
{
cout<<"In function 3"<<endl;

throw runtime_error("runtime_error in function3");
}

void function2()throw(runtime_error)//同上
{
cout<<"function3 is called inside function2"<<endl;
function3();
}

void function1()throw(runtime_error)
{
cout<<"function2 is called inside function1"<<endl;
function2();
}

int main()
{
try
{
cout<<"function1 is called inside main"<<endl;
function1();
}
catch(runtime_error &error)
{
cout<<"Exception occurred:"<<error.what()<<endl;
cout<<"Exception handled in main"<<endl;
}

return 0;
}


[解决办法]

C/C++ code
void function3()throw(runtime_error)// 函数定义后面为什么要加上throw(runtime_error)???//不加在这里也没事,加了表示只能抛出runtime_error异常{  cout<<"In function 3"<<endl;  throw runtime_error("runtime_error in function3");} 

读书人网 >C++

热点推荐