异常处理构造函数

exception handling a constructor

本文关键字:构造函数 异常处理      更新时间:2023-10-16

这是我的一个面试问题。

令人惊讶的是,我从来没有想过这种问题。

可以在构造函数中进行异常处理吗?

的时态,没有想太多,我说:"是的,我们可以在构造函数中实现。假设我们正在使用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