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

2019-05-04 01:51发布

问题:

When an unexpected exception occurs in your program (in the debugger). Sometimes you just want to skip it since killing the program at that point is more harmful than continuing. Or you just want to continue since you were more interested in another error/bug

Is there an option/compilerflag/secretswitch to enable this?

I understand exceptions should be resolved right away, but there are scenarios (like I described) where one just wants to skip it for the time-being

回答1:

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?



回答2:

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.



回答3:

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



回答4:

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!



回答5:

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.



回答6:

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.



回答7:

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.
}


回答8:

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.