本文介绍了在C ++中,“throw”和“throw ex”之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想询问 ),但这次是关于C ++。

I'd like to ask this question (also here), but this time about C++.

C ++之间的区别在于

What is the difference in C++ between

try { /*some code here*/}
catch(MyException& ex)
{ throw ex;} //not just throw

try {  /*some code here*/}
catch(MyException& ex)
{ throw;} //not throw ex


$ b b

它只是在堆栈跟踪(在C ++在任何情况下不是一个标准,如在C#或Java)?

Is it just in the stack trace (which in C++ is in any case not a standard as in C# or Java)?

(如果它有什么区别,我使用MSVS 2008.)

(If it makes any difference, I use MSVS 2008.)

推荐答案

throw; 异常对象,而 throw ex; 引发一个新的异常。除了创建新的异常对象的性能原因,它没有什么区别。如果你有一个异常层次结构,其中一些其他异常类派生自 MyException 类和抛出异常,你做了一个 throw DerivedClassException; 它可以被 catch(MyException&)捕获。现在如果你修改这个捕获的异常对象并使用 throw; 重新抛出异常对象的类型仍然会是 DerivedClassException 。如果你执行 throw Ex; ,则会发生对象切片,并且新抛出的异常类型为 MyException

throw; rethrows the same exception object it caught while throw ex; throws a new exception. It does not make a difference other than the performance reasons of creating a new exception object. If you have a exception hierarchy where there some other exception classes derived from MyException class and while throwing an exception you have done a throw DerivedClassException; it can be caught by the catch(MyException&). Now if you modify this caught exception object and rethrow it using throw; the type of exception object will still be DerivedClassException. If you do throw Ex; the object slicing occurs and the newly thrown exception will be of type MyException.

这篇关于在C ++中,“throw”和“throw ex”之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:00