一个java 类构造器 异常的bug

class Engine {

    Engine(...) throws Exception {
        // do some locking
        // do other things that could throw exception
    }

    void close() {
        // do unlocking
    }
}


public class Agent {

    Engine eng = null;
    
    public void run() {
        try {
            eng = new Engine();
            ...
        } catch (Exception e) {
            if (eng != null)
                eng.close();
        }
    }
}

 

上面的代码 有一个bug. 在Agent.run()里, 如果 new Engine()抛出exception, 则 此时 eng == null. 所以 Engine.close() 不会被调用.

字节码差不多这样:

     0  aload_0 [this]
     1  new Engine [1]
     4  dup
     5  invokespecial Engine() [18]
     8  putfield Agent.eng : Engine [19]
    11  return

可以看出, 如果在line 5处抛出exception, 则对Agent.eng的赋值不会发生.

fix: 在Engine 构造器中 catch中异常, 做unlock 操作.

posted @ 2016-02-25 12:27  brayden  阅读(262)  评论(0编辑  收藏  举报