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


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

  • 相关阅读:
    利用XAF中的FeatureCenter例子的,直接打开DetailView
    XAF 应用程序模型基础[转]
    XAF 如何给記錄增加版本控制?
    Simpler way to Create a Custom User Control
    建议将小川同志免费租借给欧洲用30年[转]文/端宏斌
    第六集 MSF构思阶段项目团队的组建
    MS_HotFix
    C#域内远程机文件信息注册表访问。
    访问 远程机 盘符 设置
    Silk_ 运行时_控件_属性_捕捉.
  • 原文地址:https://www.cnblogs.com/CocoWang/p/3700611.html
Copyright © 2020-2023  润新知