是否有任何现实世界的理由使用投掷前? [英] Is there any real world reason to use throw ex?

查看:145
本文介绍了是否有任何现实世界的理由使用投掷前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,抛出前几乎总是错的,因为它重置堆栈跟踪。

In C#, throw ex is almost always wrong, as it resets the stack trace.

我会想,有没有现实世界中使用的呢?我能想到的唯一原因是为了隐藏自己封闭库内部,但是这是一个非常弱的原因。除此之外,我从来没有在现实生活中遇到的。

I just wonder, is there any real world use for this? The only reason I can think of is to hide internals of your closed library, but that's a really weak reason. Apart from that, I've never encountered in the real world.

编辑:我的意思是抛出前,如投掷被抓,但与一个空的堆栈跟踪的确切相同的异常,如做它完全错误的。我知道,罚球前已经存在,作为一种语言结构,以允许抛出一个不同的异常(抛出新DifferentException(前为的InnerException,前)),如果只是想知道有过一个situration其中抛出前是没有错的。

I do mean throw ex, as in throwing the exact same exception that was caught but with an empty stacktrace, as in doing it exactly wrong. I know that throw ex has to exist as a language construct to allow throwing a different exception (throw new DifferentException("ex as innerException", ex)) and was just wondering if there is ever a situration where a throw ex is not wrong.

推荐答案

还有就是要重新抛出异常对象,即没有正当理由'扔恩。

There is no valid reason to re-throw exception objects i.e. 'throw ex'.

这是一个语言\编译器功能,这是可能的,虽然没有在实践上也有负面影响增加任何价值。这是一个类似的情况,能够编写code访问成员空引用 - 这当然是可能的,但是没有值,例如:

It's a language\compiler feature that's possible although doesn't add any value in practice over the negative effect it has. This is a similar situation to being able to write code to access members on null references - it's of course possible but has no value, e.g.:

    //Possible but not useful.
    object ref1 = null;

    ref1.ToString();

如果能够重新抛出异常对象是不幸的,而且往往由新秀和经验丰富的codeRS都误会了,那就是直到你得到生产未处理的异常记录截断的堆栈跟踪。

Being able to re-throw exception objects is unfortunate and very often misunderstood by rookies and experienced coders alike, that is until you get an unhandled exception in production with a truncated stack trace logged.

还有就是脆弱的感觉,它可以用来故意隐藏堆栈跟踪信息,而是抛出一个新的异常将是这样做的正确方法。

There is the tenuous feeling that it could be used to intentionally hide stack trace information, but throwing a new exception would be the correct way to do this.

我会尽可能地说,能够重新抛出异常对象(即扔恩')是一个设计缺陷去 - 它只是太容易做了错误的事情。不过,我怀疑这是一个设计权衡的编译器性能的原因,因为它会招致的开销,以验证扔恩'不是'再掷。我敢肯定有很多这样的权衡。

I would go as far as to say that being able to re-throw exception objects (i.e. 'throw ex') is a design flaw - it's just too easy to do the wrong thing. However, I suspect that this is a design trade-off in the compiler for performance reasons as it would incur an overhead to validate that 'throw ex' was not a 're-throw'. I'm sure there are many such trade-offs.

这篇关于是否有任何现实世界的理由使用投掷前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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