您的位置:首页 > 其它

(总结)try{}catch{}中有return,finally{}的执行情况

2015-11-04 17:15 337 查看
看下面的代码:

class Program
{
static void Main(string[] args)
{
int x = 0;
x = GetValue();
Console.WriteLine(" x的值为:" + x);

Console.ReadKey();
}

public static int GetValue()
{
int y = 0;
try
{
y = 1;
return ++y;
}
catch (Exception)
{
return y = 0;
}
finally
{
y = y + 1;
Console.WriteLine(" y的值为:" + y);
}
}
}


输出结果如下:

y的值为:3

x的值为:2

总结:

1、不管程序有没有错误,finally的语句都会执行;

2、当try或catch里有return语句时,程序走到return时,会先把要返回的结果临时保存起来,然后进入finally里执行,最后再把要返回的结果返回给调用者。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  try catch return finally