从构造函数捕获异常而不将对象隐藏在try块中

Jo *_* So 7 c++ exception

我有一个类,其构造函数可能会抛出异常.

class A {
    A() { /* throw exception under certain circumstances */ }
};
Run Code Online (Sandbox Code Playgroud)

我想在客户端捕获此异常以获取堆栈分配的实例.但是我发现自己被迫扩展try块,至少在实例必须存活的时候.

try {
    A a;
    do_something(a);
} catch {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

现在,当try块太大而无法追踪异常源时,这显然会成为一个问题:

try {
    A a1;
    A a2;
    do_something(a1, a2);
} catch {
    // Who caused the exception?
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能避免这种情况?

更新:

似乎我没有很好地解释这个问题:出于显而易见的原因,我想让try块跨越尽可能少的代码(也就是说,只有构造).

但是这会产生一个问题,我之后无法使用这些对象,因为它们已经超出了范围.

try {
    A a1;
} catch {
    // handle a1 constructor exception
}
try {
    A a2;
} catch {
    // handle a2 constructor exception
}

// not possible
do_something(a1, a2);
Run Code Online (Sandbox Code Playgroud)

Pub*_*bby 6

不需要更改的解决方案A是使用嵌套的try/catch块:

try {
    A a1;
    try {
        A a2;
        do_something(a1, a2);
    }
    catch {
      // a2 (or do_something) threw
    }
} catch {
    // a1 threw
}
Run Code Online (Sandbox Code Playgroud)

如果可能的话,可能最好避免这样做.