abo*_*u00 9 c# return try-catch
我写了下面的测试代码,尽管我很确定会发生什么:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
果然,该程序向控制台写了"False".我的问题是,最初返回的真实情况会发生什么?有没有办法获得这个值,如果可能的话,在catch块中,或者如果不是,在原始finally块中?
只是为了澄清,这仅用于教育目的.我永远不会在实际程序中制作这样一个复杂的异常系统.
不,这是不可能获得该值,因为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;
}
}
Run Code Online (Sandbox Code Playgroud)
但这很麻烦.出于教育目的,答案是否定的.
| 归档时间: |
|
| 查看次数: |
1616 次 |
| 最近记录: |