Using Exceptions throwing in C#. Does it affect a

2020-03-23 02:30发布

Basically, the question is: Do the Exceptions in C# affect the performance a lot? Is it better to avoid Exceptions rethrow? If i generate an exception in my code, does it affect a performance?

Sorry for the sillines of the question itself

8条回答
▲ chillily
2楼-- · 2020-03-23 02:57

Raising an exception is an expensive operation in C# (compared to other operations in C#) but not enough that I would avoid doing it.

I agree with Jared, if your application is significantly slower because of raising and throwing exceptions, I would take a look at your overall strategy. Something can probably be refactored to make exception handling more efficient rather than dismissing the concept of raising exceptions in code.

查看更多
我只想做你的唯一
3楼-- · 2020-03-23 03:11

If you're worried about exception performance, you're using them wrong.

But yes, exceptions do affect performance.

查看更多
孤傲高冷的网名
4楼-- · 2020-03-23 03:12

Microsoft's Design Guidelines for Developing Class Libraries is a very valuable resource. Here is a relevant article:

Exceptions and Performance

I would also recommend the Framework Design Guidelines book from Microsoft Press. It has a lot of the information from the Design Guidelines link, but it is annotated by people with MS, and Anders Hejlsberg, himself. It gives a lot of insight into the "why" and "how" of the way things are.

查看更多
女痞
5楼-- · 2020-03-23 03:15

running code through a try/catch statement does not affect performance at all. The only performance hit comes if an exception is thrown ... because then the runtime has to unwind the stack and gather other information in order to populate the exception object.

查看更多
ゆ 、 Hurt°
6楼-- · 2020-03-23 03:19

This is not silly just I've seen it somewhere else also on SO.

The exceptions occur well, when things are really exceptional. Most of the time you re-throw the exception (may after logging) when there are not many chances of recovering from it. So it should not bother you for normal course of execution of program.

查看更多
时光不老,我们不散
7楼-- · 2020-03-23 03:20

Exceptions in .NET do affect performance. This is the reason why they should be used only in exceptional cases.

查看更多
登录 后发表回答