简体   繁体   中英

How to debug a finally block in Visual Studio?

How do I debug the finally block in a try {...} finally{...} in the event of an uncaught exception? It seems that no matter what I do with the exception settings or debugger, Visual Studio will not let me proceed past the point of the thrown exception in the try block in order to debug the finally code.

Here's a representative, short example:

public static void Main()
{
    var instrument = new Instrument();
    try
    {
        instrument.TurnOnInstrument();
        instrument.DoSomethingThatMightThrowAnException();
        throw new Exception(); // Visual Studio won't let me get past here. Only option is to hit "Stop Debugging", which does not proceed through the finally block
    }
    finally
    {
        if(instrument != null)
            instrument.TurnOffInstrument();
    }
}

Context: I have a program that controls some hardware instruments used for taking electronic measurements in a lab, eg programmable PSUs. In the event that something goes wrong, I want it to fail fast: first shut down the instruments to prevent possible physical damage and then exit. The code to shut them down is in the finally block, but I have no way to debug that this code works in the error case. I don't want to try to handle any possible errors, just turn the instruments and then shut the program down. Maybe I'm going about this the wrong way?

  1. You can set breakpoint ( F9 key ) and Alt + Ctrl + B Keys to see the list of breakpoints.
  2. You can break in between using IntelliTrace, As :

    设置 IntelliTrace 设置

A finally block is never executed if the exception results in a crash of the application, that is the case in your code. To debug the finally block in your exemple, you have to put the whole code of your main function in an other try statement, and catch the exception to prevent the application to crash, like this:

public static void Main()
{
    try
    {
        var instrument = new Instrument();
        try
        {
            instrument.TurnOnInstrument();
            instrument.DoSomethingThatMightThrowAnException();
            throw new Exception();
        }
        finally
        {
            if (instrument != null)
                instrument.TurnOffInstrument();
        }
    }
    catch (Exception)
    {
         Console.Writeline("An exception occured");
    }
}

您需要在finally的第一行上放置一个断点,然后在异常之后再次单击“运行”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM