我编写了以下测试代码,尽管我很确定会发生什么:
static void Main(string[] args)
{
Console.WriteLine(Test().ToString());
Console.ReadKey(false);
}
static bool Test()
{
try
{
try
{
return true;
}
finally
{
throw new Exception();
}
}
catch (Exception)
{
return false;
}
}
果然,程序向控制台写入了“False”。我的问题是,最初返回的 true 会怎样?有没有什么方法可以获取这个值,如果可能的话在 catch block 中,如果不能的话在原始的 finally block 中?
澄清一下,这仅用于教育目的。我永远不会在实际程序中制作如此复杂的异常系统。
最佳答案
不,不可能得到那个值,因为毕竟只返回一个 bool
。不过,您可以设置一个变量。
static bool Test()
{
bool returnValue;
try
{
try
{
return returnValue = true;
}
finally
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("In the catch block, got {0}", returnValue);
return false;
}
}
虽然很乱。出于教育目的,答案是否定的。
关于c# - finally block 中抛出异常后的返回值会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594013/