如何使用try catch与构造函数?

Vik*_*ngh -2 c++ constructor try-catch

我看到很多例子,但我无法理解,如何使用try catch与一个简单的构造函数,我写了一个示例程序:

class A
 {
   public:
    try {
       A()
        { cout << "in costr\n"; throw 10;}
    }//try closed
   catch (int a)
{ cout << "caught 1 \n"; }

 };

main()
 {
   A *ptr = new A;
   }
Run Code Online (Sandbox Code Playgroud)
  1. 该程序给出了编译错误
  2. 如果发现异常,对象会发生什么?

pax*_*blo 6

try/catch代码应该是在一起的,你不能有一个没有其他.这样的事情就是你所追求的:

A *ptr;
try {
    ptr = new A();
} catch (int a) {
    cout << "caught 1\n";
}
Run Code Online (Sandbox Code Playgroud)

有关完整的工作示例,请参阅以下程序:

#include <iostream>

class A {
    private:
        int a;
    public:
        A() { a = 7; throw 42; }
        int getA() { return a; }
};

int main (void) {
    A *ptr;
    try {
        ptr = new A();
    } catch (int b) {
        std::cout << "Exception: " << b << '\n';
        return -1;
    }
    std::cout << "Value: " << ptr->getA() << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

随着throw 42在那里,你看:

Exception: 42
Run Code Online (Sandbox Code Playgroud)

意味着main已经捕获了来自构造函数的异常.如果没有throw,你会看到:

Value: 7
Run Code Online (Sandbox Code Playgroud)

因为一切都有效.


您的代码的主要问题似乎是:

  • 你有一个try不应该的声明.Try/catch块通常应该一个函数或方法中,你可以在public关键字之后立即使用它.

  • 如果您从构造函数中抛出异常,则不会在构造函数中捕获它.而是在调用构造函数的代码中捕获它(main在本例中).

  • 如前所述,try并且catch在一起,它们不是独立的实体.


如果你在构造函数尝试throw并且catch在构造函数中,你仍然需要将它放在构造函数本身中,例如:

#include <iostream>

class A {
    private:
        int a;
    public:
        A() {
            try {
                a = 7;
                throw 42;
            } catch (int b) {
                std::cout << "Exception A: " << b << '\n';
                throw;
            }
        }
        int getA() {return a;}
};

int main(void) {
    A *ptr;
    try {
        ptr = new A();
    } catch (int b) {
        std::cout << "Exception B: " << b << '\n';
        return -1;
    }
    std::cout << "Value: " << ptr->getA() << '\n';
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这给你:

Exception A: 42
Exception B: 42
Run Code Online (Sandbox Code Playgroud)

特别注意try/catch块是如何完成的以及构造函数的.


Rem*_*anu 5

在构造函数期间引发的异常问题由函数try块解决:

class A
 {
   public:
       A()
       try 
         { cout << "in costr\n"; throw 10;}
      catch(...)
        { cout << "exception caught"; throw;}
 };
Run Code Online (Sandbox Code Playgroud)

但他们正在解决的问题与你的例子不同.当类构造函数分配需要回收的资源时,需要函数try块.因为如果构造函数抛出(没有什么可以破坏,类没有构造开始),类的析构函数不运行,解决问题的一种方法是在构造函数上使用函数try块.注意构造函数try块必须重新抛出异常或原始异常,它们无法使异常捕获.

有关您要问的问题的更详细讨论(在构造函数中存在异常的对象的范围/生命周期),请参阅GOTW#66.


jua*_*nza 5

如果您想要做的是处理在构造函数中抛出的异常而不重新抛出它,那么您必须将 try-catch 块放在构造函数中,或者围绕着构造函数初始化列表:

class A
 {
  public:
   A() {
     try {
       // some code that could throw int
       cout << "in costr\n"; throw 10;}
     }//try closed
     catch (int a) {
       cout << "caught 1 \n";
     }
   }
   explicit A(int i) try : functionThatCanThow(i) catch (int)
   { }

 };

main()
{
   A *ptr = new A;
   A* ptr2 = new A(5);
}
Run Code Online (Sandbox Code Playgroud)