如果出现未捕获的异常,如何调试 try {...} finally{...}
中的 finally
block ?似乎无论我如何处理异常设置或调试器,Visual Studio 都不会让我越过 try
block 中抛出的异常点来调试 finally
代码。
这是一个有代表性的简短示例:
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 block 中,但我无法调试此代码在错误情况下是否有效。我不想尝试处理任何可能的错误,只需转动仪器然后关闭程序即可。也许我的做法不对?
最佳答案
如果异常导致应用程序崩溃,则永远不会执行 finally block ,这在您的代码中就是这种情况。 要调试示例中的 finally block ,您必须将 main 函数的全部代码放在另一个 try 语句中,并捕获异常以防止应用程序崩溃,如下所示:
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");
}
}
关于c# - 如何在 Visual Studio 中调试 finally block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32955393/