如果发生未捕获的异常,如何调试finally
块try {...} finally{...}
?似乎无论我如何使用异常设置或调试器,Visual Studio都不会允许我越过try
块中抛出的异常来调试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块中,但是我无法调试该代码在错误情况下的工作原理。我不想尝试处理任何可能的错误,只需打开仪器,然后关闭程序即可。也许我会以错误的方式进行操作?
如果异常导致应用程序崩溃(在您的代码中就是这种情况),则永远不会执行finally块。要调试示例中的finally块,必须将主函数的整个代码放在另一个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");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句