问一个关于try 
{}
catch
{}
 finally
{}
的问题, 如果 try中有return,那么finally里的语句是否会执行?

解决方案 »

  1.   

    引用这个帖子http://stackoverflow.com/questions/421797/what-really-happens-in-a-try-return-x-finally-x-null-statementstatic int Test() {
        try {
            return SomeNumber();
        } finally {
            Foo();
        }
    }被编译为
    .method private hidebysig static int32 Test() cil managed
    {
        .maxstack 1
        .locals init (
            [0] int32 CS$1$0000)
        L_0000: call int32 Program::SomeNumber()
        L_0005: stloc.0 
        L_0006: leave.s L_000e
        L_0008: call void Program::Foo()
        L_000d: endfinally 
        L_000e: ldloc.0 
        L_000f: ret 
        .try L_0000 to L_0008 finally handler L_0008 to L_000e
    }
    其实你可以看出,在IL层面,事实上,它只是把返回值送到运算栈的顶端,而ret是在finally之后的。
      

  2.   

    try 
    {
    //try必须执行,但可能报错,报错就中断跳到catch中
    }
    catch
    {
    //如果try块中代码报错就执行
    }
    finally
    {
    //无论如何都要执行,没有任何形式可以中断。
    }
      

  3.   

     在finally里面你写一个打印字符串程序看看就知道了...