using System;public class Test5
{
private void func()
{
//1
try
{
//2
Console.WriteLine("2");
//3
throw new ApplicationException();
//4
Console.WriteLine("3");
}
catch (ApplicationException e)
{
//5
Console.WriteLine("5");
throw new Exception();
}
catch (Exception e)
{
//6
Console.WriteLine("6");
}
finally
{
//7
Console.WriteLine("7");
} //8
Console.WriteLine("8");
} public void test()
{
try
{
//9
func();
}
catch (Exception e)
{
//10
Console.WriteLine("10");
}
finally
{
//11
Console.WriteLine("11");
}
} static void Main(string[] args)
{
//12
(new Test5()).test();
}
}
为什么输出是



10 
11
在//5处throw了为什么还会执行finally?

解决方案 »

  1.   

    finally的作用就是确保程序无论如何都要执行的代码。(当然不要考虑意外情况,比如刚好停电)在你的try/catch/finally结构退出前,就会执行finally里的。
      

  2.   

    呵呵,直接抛出本来就该执行Finally了只有try才能捕获异常如果想截获 5 出的抛出,  catch (ApplicationException e)
    {
    //5
                           try
                            {
    Console.WriteLine("5");
    throw new Exception();
                             }
                            catch (Exception e)
                             {
    Console.WriteLine("只有try才能捕获异常");                            
                              }
    }
    catch (Exception e)
    {
    //6
    Console.WriteLine("6");
    }
    finally
    {
    //7
    Console.WriteLine("7");
    }