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

2020-11-22 18:26

阅读:850

标签:style   blog   class   java   ext   int   string   http   line   com   name   

博客原文: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();
    }
}

C#,Java,C++中的finally关键字,搜素材,soscw.com

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

标签:style   blog   class   java   ext   int   string   http   line   com   name   

原文地址:http://www.cnblogs.com/CocoWang/p/3700611.html


评论


亲,登录后才可以留言!