罚球和抛出新的异常之差() [英] difference between throw and throw new Exception()

查看:122
本文介绍了罚球和抛出新的异常之差()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就是

try { ... }
catch{ throw } 

try{ ... }
catch(Exception e) {throw new Exception(e.message) } 

无论第二显示消息?

Regardless that the second shows a message ?

推荐答案

抛出; 重新抛出原来的异常和preserves原来的堆栈跟踪

throw; rethrows the original exception and preserves its original stack trace.

罚球前; 抛出原来的异常,但重置堆栈跟踪,摧毁所有的堆栈跟踪信息,直到你的块。

throw ex; throws the original exception but resets the stack trace, destroying all stack trace information until your catch block.



抛出新的异常(ex.Message); 更是雪上加霜。它创建了一个全新的例外实例,失去了异常的原始堆栈跟踪,以及它的类型。 (例如, IOException异常)。结果
此外,一些例外举行额外信息(例如, ArgumentException.ParamName )。结果
抛出新的异常(ex.Message); 也将破坏这个信息

throw new Exception(ex.Message); is even worse. It creates a brand new Exception instance, losing the original stack trace of the exception, as well as its type. (eg, IOException).
In addition, some exceptions hold additional information (eg, ArgumentException.ParamName).
throw new Exception(ex.Message); will destroy this information too.

在某些情况下,你可能想要包装的定制异常对象的所有异常,这样就可以提供什么异常时抛出的code在做其他信息。

In certain cases, you may want to wrap all exceptions in a custom exception object, so that you can provide additional information about what the code was doing when the exception was thrown.

要做到这一点,定义继承例外补充说,需要一个的InnerException 以及其他信息全部四个例外构造 ,和任选的额外的构造函数,抛出新的异常类,的通过的InnerException 参数的。通过将原始的的InnerException ,你preserve所有原始异常的属性,包括堆栈跟踪。

To do this, define a new class that inherits Exception, add all four exception constructors, and optionally an additional constructor that takes an InnerException as well as additional information, and throw your new exception class, passing ex as the InnerException parameter. By passing the original InnerException, you preserve all of the original exception's properties, including the stack trace.

这篇关于罚球和抛出新的异常之差()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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