從constructor中拋出exception後,constructor會返回null嗎?

剛纔琢磨這個問題主要是在想,若是constructor拋出了exception,那麼返回的object是什麼一個狀況呢?若是我這個object中有一些關鍵的資源沒有初始化,好比說Database connection在建立的時候有可能拋出SQLException,會不會返回一個HALF-MADE的object呢?爲了驗證,寫了以下代碼,結論:若是constructor中拋出了exception,constructor不會返回任何object,甚至null也不會返回。(由於程序流程在執行到return以前就跳轉到exception處理去了啊親,固然不會return任何東西!)java

class Box {
    private final int number; 
    public Box(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Negative number: " + number);
        }
        this.number = number;
    }
    public int getNumber() {
        return number;
    }
}

public class Foo {

    public static void main(String[] args)  {
        Box box = new Box(999);
        try {
            box = new Box(-999);
        } catch (IllegalArgumentException e) {
            // ignored
        }
        System.out.println(box);
    }
    
}

回到我剛纔遇到的問題,通過這番思考以後,我改寫了一下,使用了一個static factory method(固然,針對我這裏的狀況而言,其實使用constructor也是能夠的)ui

// Data Source
public class DatabaseConnection {
    // data source name
    private static final String DSNAME = "java:comp/env/jdbc/fooooooooooooo";
    private Connection conn = null;
    private DatabaseConnection(Connection conn) {
        this.conn = conn;
    }
    /**
     * Construct a new instance of DatabaseConnection. 
     * @return a new instance of DatabaseConnection.
     * */
    public static DatabaseConnection newInstance() throws NamingException, SQLException {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup(DSNAME);
        Connection conn = ds.getConnection();
        return new DatabaseConnection(conn);
    }
    public Connection getConnection() {
        return conn;
    }
    public void close() throws SQLException {
        conn.close();
    }
}

我搜索了3篇有關constructor的問題,值得一看this

一、Is it good practice to make the constructor throw an exception?spa

  裏面討論了從constructor拋出exception是否是good practicecode

  值得一提的是,裏面還討論了檢查argument的正確性應該用exception仍是assertionblog

二、Is doing a lot in constructors bad?資源

三、How much code should one put in a constructors (Java)?get

  2和3討論了constructor應該作哪些工做,不該該作哪些工做,作多少工做合適,以及在什麼狀況下應該考慮使用Factory或者Builderit

相關文章
相關標籤/搜索