【问题标题】:Is the C++ exception out of scope if caught by the outter level caller?如果被外部级别调用者捕获,C++ 异常是否超出范围?
【发布时间】:2013-01-25 14:36:21
【问题描述】:

我做了一些研究,试图找到在我遇到的代码中实现异常的正确方法

    Throw by value, catch by reference

成为 C++ 中处理异常的推荐方式。我对抛出的异常何时超出范围感到困惑。

我有以下异常层次结构

    ConnectionEx is mother of all connection exceptions thrown by dataSender
    ConnectionLostEx is one of the subclasses of ConnectionEx

所以这里是一个示例代码。换句话说,DataSender 实例是 DataDistrubutor 的成员,它调用 dataSender 上的函数,例如 send() 并且 DataSender 在出现问题时将 ConnectionEx 的子类作为异常抛出。

// dataSender send() function code chunk

try
{
   // some problem occured
       // create exception on stack and throw
   ConnectionLostEx ex("Connection lost low signals", 102);
   throw ex;
}
catch(ConnectionLostEx& e)
{
    //release resources and propogate it up
    throw ;
}

//A data distributor class that calls dataSender functions
try
{
    // connect and send data
    dataSender.send();  
}
catch(ConnectionEx& ex)
{
       // free resources
       // Is the exception not out of scope here because it was created on stack of orginal block?
       //propogate it further up to shows cause etc..

}

在 C# 或 java 中,我们有一个类似引用的指针,并且它一直有效,我对异常的范围感到困惑,因为异常是由值抛出的,什么时候超出范围???在这种情况下,当被捕获为父类型 ConnectionEx 时,是否可以强制转换以使真正的返回到捕获块链中的某个位置??

【问题讨论】:

    标签: c++ exception


    【解决方案1】:

    抛出异常的副本,而不是原始对象。无需实例化局部变量并抛出它;抛出异常的惯用方法是实例化它并在同一行抛出它。

    throw ConnectionLostEx("Connection lost low signals", 102);
    

    【讨论】:

    • 如果抛出一个副本,在 catch 块中使用引用的目的是什么?
    • @Ahmed:副本是抛出,而不是捕获。
    • 我明白了,所以当一个特定的 catch 块完成时,它得到的副本被销毁,但它可能已经抛出另一个副本来转发它。这是正确的吗?
    • @Ahmed 如果您通过复制捕获--catch (Exception e)--那么您将获得异常对象的副本,并且该副本在捕获块退出时被销毁。如果你通过引用捕获--catch (Exception &e)--那么你得到了对原始异常对象的引用,并且没有副本。
    • @JohnKugelman:副本不一定会传播,除非您再次调用throw;。
    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多