C++ 是C++;异常超出范围(如果被外层调用方捕获)?

C++ 是C++;异常超出范围(如果被外层调用方捕获)?,c++,exception,C++,Exception,我做了一些研究,同时试图找到合适的方法来实现我遇到的代码中的异常 Throw by value, catch by reference 是C++中处理异常的推荐方法。我对抛出的异常何时超出范围感到困惑 我有以下异常层次结构 ConnectionEx is mother of all connection exceptions thrown by dataSender ConnectionLostEx is one of the subclasses of Connect

我做了一些研究,同时试图找到合适的方法来实现我遇到的代码中的异常

    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实例是DataDistributor的成员,它调用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时,是否可以将其转换为将真正的一个返回到捕获块链中的位置???

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

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

如果抛出一个副本,在catch块中使用引用的目的是什么?@Ahmed:抛出一个副本,而不是捕获。我明白了,所以当某个catch块完成时,它得到的副本被销毁,但它可能抛出了另一个副本来转发它。这是否正确?@Ahmed如果您按副本捕获--
catch(异常e)
,则您将获得异常对象的副本,并且当catch块退出时,该副本将被销毁。如果通过引用捕获--
catch(Exception&e)
,则获得对原始异常对象的引用,并且没有副本。@JohnKugelman:除非调用
throw再一次。