在C#多少性能损失的是一个尝试,投掷和catch块 [英] Under C# how much of a performance hit is a try, throw and catch block

查看:185
本文介绍了在C#多少性能损失的是一个尝试,投掷和catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,免责声明:
我在其他语言的经验,但我仍然在学习C#

First of all, a disclaimer: I have experience in other languages, but am still learning the subtleties of C#

微妙之处上的问题.. 。我在看一些代码,它使用try / catch块在我所关心的一种方式。当解析程序被调用,而不是返回一个错误代码,程序员使用以下逻辑

On to the problem... I am looking at some code, which uses the try/catch blocks in a way that concerns me. When a parsing routine is called, rather than return an error code, the programmer used the following logic

catch (TclException e) {
  throw new TclRuntimeError("unexpected TclException: " + e.Message,e);
}

这是由主叫方,这引发了同样的错误捕获...

...这是由主叫方抓到,会抛出同样的错误......

.....这是由主叫方抓到,会抛出同样的错误...

This is caught by the caller, which throws the same error ...
... which is caught by the caller, which throws the same error ...
..... which is caught by the caller, which throws the same error ...

回升约6的水平。

我是正确的思维所有这些捕获/扔块是造成性能问题,或者这是在C#中的合理的实现?

Am I right in thinking all these catch/throw blocks are causing a performance problem, or is this a reasonable implementation under C#?

推荐答案

掷(而不是抓)是昂贵的。

Throw (rather than catch) is expensive.

不要把除非你打算做一些有益的catch块(即转换为更实用的异常,处理错误)。

Don't put a catch block in unless you are going to do something useful (i.e. convert to a more useful exception, handle the error).

只是重新抛出异常(无参数throw语句),或者更糟糕,扔相同的对象刚好赶上绝对是错误的事情。

Just rethrowing the exception (throw statement without argument) or, even worse, throw the same object as just caught is definitely the wrong thing.

编辑:为了避免歧义:

重新抛出:

catch (SomeException) {
  throw;
}



创建一个从以前的异常对象,所有的运行时提供国家(特别是堆栈异常跟踪)被改写:

Create exception from previous exception object, where all the runtime provided state (notably stack trace) is overwritten:

catch (SomeException e) {
  throw e;
}



后一种情况扔掉有关异常的信息,一个毫无意义的方式。并没有在catch块扔前面的东西是双重意义。它可以是更糟糕的:

The latter case is a pointless way to throw away information about the exception. and without anything preceding the throw in the catch block is doubly pointless. It can be worse:

catch (SomeException e) {
  throw new SomeException(e.Message);
}



而失去几乎所有有用的状态信息Ë包含(包括了最初抛出。)

which loses almost all the useful state information e contained (including what was originally thrown.)

这篇关于在C#多少性能损失的是一个尝试,投掷和catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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