8

我有一个类,其构造函数可能会引发异常。

class A {
    A() { /* throw exception under certain circumstances */ }
};

我想在客户端中为堆栈分配的实例捕获此异常。但我发现自己被迫try至少在实例必须存活的情况下扩展块。

try {
    A a;
    do_something(a);
} catch {
    // ...
}

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

try {
    A a1;
    A a2;
    do_something(a1, a2);
} catch {
    // Who caused the exception?
}

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

更新

似乎我没有很好地解释这个问题:出于显而易见的原因,我希望 try 块跨越必要的代码(即,仅构建)。

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

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

// not possible
do_something(a1, a2);
4

3 回答 3

7

A solution that doesn't require changing A is to use nested try/catch blocks:

try {
    A a1;
    try {
        A a2;
        do_something(a1, a2);
    }
    catch {
      // a2 (or do_something) threw
    }
} catch {
    // a1 threw
}

Probably better to avoid doing this if possible though.

于 2013-01-07T21:28:24.927 回答
4

Use heap-constructed objects instead of stack-constructed objects, so that you can test which objects have been constructed successfully, eg:

// or std::unique_ptr in C++11, or boost::unique_ptr ...
std::auto_ptr<A> a1_ptr;
std::auto_ptr<A> a2_ptr;

A *a1 = NULL;
A *a2 = NULL;

try
{
    a1 = new A;
    a1_ptr.reset(a1);
}
catch (...)
{
}

try
{
    a2 = new A;
    a2_ptr.reset(a2);
}
catch (...)
{
}

if( (a1) && (a2) )
    do_something(*a1, *a2);

Alternatively (only if A is copy-constructible):

boost::optional<A> a1;
boost::optional<A> a2;

try
{
    a1 = boost::in_place<A>();
    a2 = boost::in_place<A>();
}
catch (...)
{
    //...
}

if( (a1) && (a2) )
    do_something(*a1, *a2);
于 2013-01-07T21:28:21.067 回答
0

在某些情况下可能很方便的另一种方法:

class ExceptionTranslatedA : public A {
public:
    template<typename Exc>
    ExceptionTranslatedA(Exc exc)
    try : A() {}
    catch (unhelpful_generic_exception) {
        throw exc;
    }
};

如果您只想在原始 try-catch 块中抛出不同的异常,这将特别有用,因为您可以完全摆脱它。它也感觉比为控制流引入布尔变量更优雅(即使它们隐藏在boost::optionals 中)。

于 2015-12-12T00:09:12.613 回答