Under C# how much of a performance hit is a try, throw and catch block

前端 未结 8 605
孤街浪徒
孤街浪徒 2020-12-15 22:07

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

On to the problem... I am looking at some code, which u

8条回答
  •  情歌与酒
    2020-12-15 22:40

    In general, throwing an exception is costly in .NET. Simply having a try/catch/finally block is not. So, yes, the existing code is bad from a performance perspective because when it does throw, it throws 5-6 bloated exceptions without adding any value over simply letting the original exception naturally bubble up 5-6 stack frames.

    Worse yet, the existing code is really bad from a design perspective. One of the main benefits of exception handling (as compared to returning error codes) is that you don't need to check for exceptions/return codes everywhere (in the call stack). You need only catch them at the small number of places you actually want to handle them. Ignoring an exception (unlike ignoring a return code) doesn't ignore or hide problem. It just means it'll be handled higher up the call stack.

提交回复
热议问题