Evan Cox
Evan Cox

Reputation: 189

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, e.g. 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?

Upvotes: 4

Views: 1286

Answers (3)

Cyril Seguenot
Cyril Seguenot

Reputation: 102

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");
    }
}

Upvotes: 2

Er Mayank
Er Mayank

Reputation: 1073

  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 :

    Set IntelliTrace Settings

Upvotes: 2

You need to put a breakpoint on the first line inside the finally block, then click "Run" again after the exception.

Upvotes: 1

Related Questions