异常处理构造函数
exception handling a constructor
这是我的一个面试问题。
令人惊讶的是,我从来没有想过这种问题。
可以在构造函数中进行异常处理吗?
的时态,没有想太多,我说:"是的,我们可以在构造函数中实现。假设我们正在使用new操作符为指针成员分配一些内存,它抛出了一个糟糕的alloc异常,这样就有可能引发异常"
后来我想到构造函数永远不能返回值。那么构造函数中的异常如何被捕获呢?现在我问我自己这个问题!
有谁能帮我摆脱这个困惑吗?请参阅GOTW构造函数失败问题,该问题在一定程度上解决了您的查询,并继续说这是浪费时间。
构造函数没有返回类型,所以不能用return代码。这是最好的信号因此构造函数失败是抛出异常。如果你没有使用异常的选项"最不坏"的解决方法是把对象进入"僵尸"状态设置一个内部状态位物体就像死了一样尽管它在技术上是静止的活着。
可以在调用代码中捕获异常,而不是在构造函数中。
参见如何处理失败的构造函数?要了解更多细节(实际上,我建议阅读有关异常处理的整个页面,这确实很有启发)。
异常处理和返回类型完全不同。当程序在构造函数中发现异常时,它将异常抛出到几乎由catch块[如果使用]或抛出到调用者(main())。在这种情况下,我们在构造函数中有catch块,并由它处理异常。一旦异常处理,构造函数/函数中的剩余语句将开始执行。请看下面的例子,
class A
{
public:
A(){
printf("Hi Constructor of An");
try
{
throw 10;
}
catch(...)
{
printf("the String is unexpected one in constructorn");
}
printf("Hi Constructor of An");
}
~A(){
printf("Hi destructor of An");
}
};
int main()
{
try{
A obj ;
throw "Bad allocation";
}
catch(int i)
{
printf("the Exception if Integer is = %dn", i);
}
catch(double i)
{
printf("the Exception if double is = %fn", i);
}
catch(A *objE)
{
printf("the Exception if Object n");
}
catch(...)
{
printf("the Exception if character/string n");
}
printf("Code endsn");
return 0;
}
输出:
Start: Constructor of A
the String is unexpected one in constructor
End: Constructor of A
Hi destructor of A
the Exception if character/string
Code ends
c++有类似于其他语言的try-catch子句。教程可以在网上找到:http://www.cplusplus.com/doc/tutorial/exceptions/
编辑:示例变成完整的工作代码
#include <iostream>
using namespace std;
class A
{
public:
void f(){
throw 10;
}
A(){
try{
f();
}
catch(int e){
cout << "Exception caughtn";
}
}
};
int main (int argc, const char * argv[])
{
A a;
return 0;
}
输出:
Exception caught
相关文章:
- std::string 构造函数如何处理固定大小的 char[]?
- 如何编写移动构造函数以处理非初始化的移动
- 如何使用unique_ptr声明调用构造函数并处理程序终止信号
- 智能指针和构造函数异常
- 构造函数C++异常说明符
- 是否可以对构造函数抛出异常的对象进行异常处理,该对象的异常处理接近其基于堆栈的代码创建
- 如何使用move构造函数正确处理shared_ptr的映射
- boost::archive::text_iarchive构造函数异常
- C++堆栈对象的构造函数异常处理
- 默认构造函数C++异常不会引发吗?
- 如何与命名构造函数一起处理不可复制的成员
- 构造函数中处理的异常已传播回.怎样
- 当函数中静态变量的构造函数异常终止时会发生什么
- 移动构造函数:如何处理容器属性
- 在c++中,如果基类构造函数异常,则构造函数和析构函数的顺序可以是这样
- 如何捕获构造函数异常
- C++构造函数异常处理
- 捕获构造函数异常的RAII方法
- 默认复制构造函数是否处理常量
- Std::unique_ptr::reset和构造函数异常