Mr.*_*bis 3 c++ exception-handling
请看一下演示代码:
class myError
{
const char* str;
public:
myError():str(NULL) {}
myError(const char* temp)
{
str = temp;
}
const char* what()
{
return str;
}
};
class ab
{
int x;
public:
ab() try :x(0)
{
throw myError("error occured in the constructor of class ab");
}
catch(myError& temp)
{
std::cout<<"Handler no. 1 of ab constructor"<<std::endl;
}
};
int main () try
{
ab bb;
cout << "Resumed execution!" << endl;
return 0;
}
catch(myError& temp)
{
std::cout<<"Handler below the main function"<<std::endl;
std::cout<<"And the error is :" <<temp.what();
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
当你只是在ctor中抛出异常时,它的处理程序不会重新抛出对象?即
Ctor::Ctor()
{
try{
throw Excep1();
}
catch(Excep1& temp) {
std::cout<<"Doesn't rethrows the exception object";
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道cout << "Resumed execution!" << endl;在处理rethrown对象后如何恢复控制权?
为什么经常说我们不应该在基类的dtor上放置函数try块?
通常的规则是,catch除非您要求,否则不会重新生成块.如何阻止异常传播.但是,对于构造函数,如果初始化列表中的某些内容抛出,那么您没有完全构造的对象; 你无法用对象做任何事情,甚至不能在它上面调用析构函数.如果catch构造函数的功能块没有重新抛出,它会做什么,因为它不能简单地返回(并将变量留在堆栈上)?
在所有其他情况下,包含catch块的功能是要知道该怎么做.例如,对于main,你可以写:try {ab bb; } catch(...){} std :: cout <<"恢复执行!" << std :: endl;
你不能做的是执行bb范围和可访问的代码,但是没有正确构造.
至于为什么你不应该在基类的析构函数上放置一个函数try块,我从来没有听说过这个规则.一般来说,析构函数不应该抛出,因此将它们包装在try块中是没有意义的.
| 归档时间: |
|
| 查看次数: |
149 次 |
| 最近记录: |