如何在Visual Studio中调试finally块? [英] How to debug a finally block in Visual Studio?

查看:58
本文介绍了如何在Visual Studio中调试finally块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果发生未捕获的异常,如何在 try {...}最后{...} 中调试 finally 块?似乎无论我如何使用异常设置或调试器,Visual Studio都不会让我继续通过 try 块中抛出的异常的点来调试 finally 代码.

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

上下文:我有一个程序,可以控制一些用于在实验室中进行电子测量的硬件仪器,例如可编程PSU.万一出问题了,我希望它能快速失败:首先关闭仪器以防止可能的物理伤害,然后退出.关闭它们的代码在finally块中,但是我无法调试该代码在错误情况下的工作原理.我不想尝试处理任何可能的错误,只需打开仪器,然后关闭程序即可.也许我会以错误的方式进行操作?

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?

推荐答案

如果异常导致应用程序崩溃(在您的代码中就是这种情况),则永远不会执行finally块.要调试示例中的finally块,必须将主函数的整个代码放在另一个try语句中,并捕获异常以防止应用程序崩溃,如下所示:

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

这篇关于如何在Visual Studio中调试finally块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆