C#,Java,C++中的finally关键字

时间:2024-01-17 20:33:14

博客原文:http://hankjin.blog.163.com/blog/static/33731937201031511305338/

先说C++,标准C++不支持finally, 如果要实现finally的效果,可以用析构函数来实现: class File_handle {
   FILE* p;
public:
   File_handle(const char* n, const char* a)
    { p = fopen(n,a); if (p==0) throw Open_error(errno); }
   File_handle(FILE* pp)
    { p = pp; if (p==0) throw Open_error(errno); }

~File_handle() { fclose(p); }

operator FILE*() { return p; }

// ... };

C#和Java基本一致 以C#为例 无论是否有异常,理论上finially都会在最后被调用,实际上,要确保在执行到finally之前没有Exit 正常流程:注释掉2,运行流程为1-》3-》8-》7 异常流程:注释掉3和5,运行流程为1-》2-》4-》6-》8-》7 退出流程:注释掉3,运行流程为1-》2-》4-》5,注意这里finally没有被调用 C#代码 namespace CXX
{
    class TestX
    {
        public TestX()
        {
            Console.WriteLine("TestX constructor");//8
        }
    }
    class Program
    {
        static TestX f()
        {
            try
            {
                Console.WriteLine("Enter F");//1
                throw new Exception("Tester");//2
                return new TestX();//3
            }
            catch (Exception)
            {
                Console.WriteLine("Except caught");//4
                System.Environment.Exit(0);//5
                return new TestX();//6
            }
            finally
            {
                Console.WriteLine("Finaly");//7
            }
        }
        static void Main(string[] args)
        {
            Program.f();
        }
    }
} Java代码: class A{
    public A(){
        System.out.println("A construct");//8
    }
}
public class Test{
    static A f(){
        try{
            System.out.println("Worked");//1
            throw new Exception("Ok");//2
            return new A();//3
        }
        catch(Exception e){
            System.out.println("Except");//4
            System.exit(1);//5
            return new A();//6
        }
        finally{
            System.out.println("Finaled");//7
        }
    }
    public static void main(String args[])throws
Exception{
        Test.f();
    }
}