unhandled exception at try catch affect performance [closed]

∥☆過路亽.° 提交于 2019-12-13 08:57:55

问题


I am working in a C# Desktop application
I had made some code such that on execution of that code it falls into the catch block

try
{

        //come code

}
catch(exception ex)
{

}
  //some code 2

where I have not handled the exception because i want to excecute the code outside the catch block
'some code 2'

but on unhandling the exception it decreases the performance of execution

so please any alter solution for this


回答1:


Don't use exceptions for normal program flow. Exceptions are not optimised for speed, because they are normally used in situations where the performance no longer matters.

When the exception is created, it gathers a lot of information that could be used to troubleshoot the error, so that takes some time. If you have compiled the code in debug mode it will collect even more information, taking even more time to do so.

Whatever you are doing that causes the exception, try to catch that condition before it causes the actual error. For example if you are catching a division by zero, you should check the value that you are dividing by before doing the division.




回答2:


You should restructure your code to avoid using exceptions for control flow.

Exceptions should be reserved for exceptional things. There is a performance overhead in throwing and catching an exception, that cannot be avoided. Much of the overhead comes from capturing the stack trace, call site and other info to put in the exception.

Also be aware, that debug mode adds significantly to the time take to process an exception. (So if you haven't tried it in Release mode yet, perhaps you should try that first - though the advice in the first line of this answer still apply).

See also Exceptions and Performance on MSDN; there are also good resources to be found in this previous question and answer: How expensive are exceptions in C#?.




回答3:


Throwing and catching an exception does have an impact on performance, but that's not the biggest problem with your code. Swallowing an exception like this is bad practice, and it's also not a good idea to catch System.Exceptions. Generally speaking, you should only catch exceptions you can reasonably handle and allow anything else to bubble up. If you want to execute code after your try block, regardless of whether an exception occurs, consider using a finally block. For example:

try
{
    // some code
}
finally
{
    // some code 2
}

Or possibly you can reorganize your code to avoid using a try-catch or try-finally at all.

You may want to create a global exception handler for your app, most likely using the AppDomain.UnhandledException event, for logging, etc.



来源:https://stackoverflow.com/questions/18945681/unhandled-exception-at-try-catch-affect-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!