is there a way to continue an exception in C#?

蓝咒 提交于 2019-12-05 17:53:15

You can't do this without an appropriate catch block in your code, no. However, I can't remember ever wanting to do this: if an exception occurs which your code doesn't know how to genuinely handle, why would you want to continue? You're in a bad state at that point - continuing would be dangerous.

Can you give an example of why you'd want to continue in a debugger session but not in production code?

reinierpost

Exceptions in C# are not resumable, but events are - and that is how resumable exceptions are typically implemented: as cancellable events. See also this question.

Use a try-catch block, and when catching, don't do anything about the exception.

If you are into the debugger then right click on the line you want to continue and select: Set Next Statement... but use it at your own risk!

When stepping through the code in debug mode you could skip the execution of the instructions that throw the undesired exception. But if the exception is already thrown and you don't have a try/catch it will propagate.

Have a look at the Exception Handling Application Block and related documentation. It contains best practices for handling application exceptions and there is a lot of framework code done for you i.e. logging.

If you want to know what exception you want to allow. then you can do this below

try
{
       // your functionality
}
catch(Exception ex)
{
     // Catch only the exceptions you need to point out
}
finally
{
   //do what you want to complete with this function.
}

I assume that by "skipping" you mean that you want your program to continue working after the exception. That, of course, is possible by catching the exception when using try-catch block.

If the exception is not application stopper (for example, some key variable is not initialized after the exception, and you can't continue work) it is recommended that you at least log it before continue. Of course, putting

catch (Exception e) { }

everywhere in your source will not lead to a stable application ;)

If your problem is more debugger-related (you don't want the debugger to stop on every thrown exception), then there is a place in VS where you can change this:

In the Debug menu, select Exceptions. You'll see all possible exceptions and you can adjust their behaviour when thrown or not handled by the user.

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