1

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

    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 被捕获时,是否可以将其转换为真正的返回到捕获块链中的某个位置?

4

1 回答 1

3

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

throw ConnectionLostEx("Connection lost low signals", 102);
于 2013-01-25T14:40:44.433 回答