using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace test_try_catch_finally
{
class Program
{
private static bool OpenFile()
{
bool ret = false;
try
{
try
{
File.Open(@"C:\windows\notepad.x", FileMode.Open);
ret = true;
}
catch (Exception ex)
{
throw ex;
Console.WriteLine("Exception:{0}", ex.Message);
ret = true;
}
finally
{
Console.WriteLine("Finally");
ret = true;
}
Console.WriteLine("ret:{0}", ret.ToString());
return ret;
}
catch (Exception ex)
{
Console.WriteLine("Exception:{0}", ex.Message);
ret = false;
}
Console.WriteLine("ret:{0}", ret.ToString());
return ret;
}
static void Main(string[] args)
{
Console.WriteLine("RET:{0}", OpenFile());
Console.ReadKey();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
以上代码测试结果,觉得它的执行顺序很值得纪录:
首先在底层的顺序是, try中File.Open(@"C:\windows\notepad.x", FileMode.Open);报错后,跳进底层catch块执行完throw后,接着马上跳进底层finally块执行完,接着就跳进上层的catch块了,执行完上层catch后,最后去执行完上层catch块后面的Console.WriteLine("ret:{0}", ret.ToString()); return ret;
--------------------------致此,函数的调用得以完成.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace test_try_catch_finally
{
class Program
{
private static bool OpenFile()
{
bool ret = false;
try
{
try
{
File.Open(@"C:\windows\notepad.x", FileMode.Open);
ret = true;
}
catch (Exception ex)
{
return false;
throw ex;
Console.WriteLine("Exception:{0}", ex.Message);
ret = true;
}
finally
{
Console.WriteLine("Finally");
ret = true;
}
Console.WriteLine("ret:{0}", ret.ToString());
return ret;
}
catch (Exception ex)
{
Console.WriteLine("Exception:{0}", ex.Message);
ret = false;
}
Console.WriteLine("ret:{0}", ret.ToString());
return ret;
}
static void Main(string[] args)
{
Console.WriteLine("RET:{0}", OpenFile());
Console.ReadKey();
}
}
}
下面的因为低层的catch中有return false;在throw ex;之前,所以在catch中走完return false;之后,直接跳进底层finally块执行完,函数就调用结束了...