本文介绍了在catch块中引发异常会导致两个异常在飞行中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下C ++代码:

Consider the following C++ code:

class MyException {};

void someFunction()
{
    try
    {
        /// ... code that may throw
    }
    catch(std::exception& e )
    {
        throw MyException();
    }
}



问题



异常e在catch块的开头或catch块的末尾被吸收吗?

Question

Is the exception e absorbed at the beginnging of the catch block or at the end of the catch block?

在第二种情况下,抛出新的异常将导致在飞行中有两个异常,什么不是我想要的。我想吸收std :: exception并启动我自己的一个类型。

In the second case throwing the new exception would result in having two exceptions in flight, what is not what I want. I want to absorb the std::exception and start one of my own type.

推荐答案

这是怎么做的。只有在第一个异常被捕获并因此不再在飞行中时,才能发生 throw myException()

No. That's how one should do it. The throw myException() can only occur if the first exception has been caught and hence is no longer 'in flight'.

这种设计模式是很常见的翻译错误消息来自另一个库,您的代码正在使用的错误,您的代码的用户可以更好地与。

This design pattern is quite common to 'translate' error messages coming from another library that your code is using to an error that the user of your code can better relate to.

或者,如果你想做的不仅仅是 throw (比如你想做一些清理资源 - 虽然这应该是通过RAII完成的,即从析构函数),那么你可以通过

Alternatively, if you want to do more than merely throw (say you want to do some clearing up of resources -- though that should really be done via RAII, i.e. from destructors), then you can simply rethrow the original exception via

try
{
    // ... code that may throw
}
catch(...) // catches anything
{
    // ... code that runs before rethrowing
    throw;    // rethrows the original catch
}

这篇关于在catch块中引发异常会导致两个异常在飞行中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:04