在C ++中,“throw”和“throw ex”之间有区别吗? [英] In C++, is there a difference between “throw” and “throw ex”?
问题描述
C ++之间有什么区别?
try {/ * some code here * /}
/ pre>
catch(MyException& ex)
{throw ex;} //不只是抛出
和
try {/ * some code here * /}
catch(MyException& ex)
{throw;} //不抛出
它只是在堆栈跟踪(C ++中的C#或Java中的标准)在
(如果它有任何差异,我使用MSVS 2008)。
解决方案
throw;
重新抛出在throw ex;
引发新的异常时捕获异常对象。除了创建新的异常对象的性能原因之外,它没有什么不同。如果你有一个例外层次结构,其中有一些其他异常类派生自MyException
类,同时抛出异常,你已经完成了一个throw DerivedClassException;
它可以被catch(MyException&)
抓住。现在,如果您修改此捕获的异常对象并使用throw;
重新抛出异常对象的类型仍将为DerivedClassException
。如果您执行throw Ex;
,则会发生对象切片,新抛出的异常将为MyException
。I'd like to ask this question (also here), but this time about C++.
What is the difference in C++ between
try { /*some code here*/} catch(MyException& ex) { throw ex;} //not just throw
and
try { /*some code here*/} catch(MyException& ex) { throw;} //not throw ex
Is it just in the stack trace (which in C++ is in any case not a standard as in C# or Java)?
(If it makes any difference, I use MSVS 2008.)
解决方案
throw;
rethrows the same exception object it caught whilethrow 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 fromMyException
class and while throwing an exception you have done athrow DerivedClassException;
it can be caught by thecatch(MyException&)
. Now if you modify this caught exception object and rethrow it usingthrow;
the type of exception object will still beDerivedClassException
. If you dothrow Ex;
the object slicing occurs and the newly thrown exception will be of typeMyException
.这篇关于在C ++中,“throw”和“throw ex”之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!