在C ++中,“throw”和“throw ex”之间有区别吗? [英] In C++, is there a difference between “throw” and “throw ex”?

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

问题描述

我想要这个问题(也此处 ),但这次是关于C ++。



C ++之间有什么区别?

  try {/ * some code here * /} 
catch(MyException& ex)
{throw ex;} //不只是抛出
/ pre>

  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 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”之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆