Java什麼時候拋出異常什麼時候try-catch?

最近在寫JDBC的工具類
寫到getConnection方法和close方法時,產生了疑惑。

/**
 * 獲取連接
 * @return 連接對象
 */
public static Connection getConnection() throws SQLException {

    return DriverManager.getConnection(url, user, password);
}

/**
 * 釋放資源
 * @param stmt
 * @param conn
 */
public static void close(Statement stmt,Connection conn){
    if( stmt != null){
        try {
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if( conn != null){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

疑惑是爲什麼getConnection方法時處理
DriverManager.getConnection(url, user, password);
的異常時拋出了SQLException,爲什麼不try-catch

爲什麼close釋放資源的時候採用的是try-catch而不是拋出

關鍵點分析:
1、throw 異常之後,後面的代碼將不會執行
2、try-catch時,即使catch到了異常之後,後面的代碼還是會繼續執行

getConnection時沒有必要採用trycatch 因爲如果連數據庫都連接不上,就不用談後面對數據庫的操作了。

釋放資源的時候trycatch是必要的,因爲不止關了一個資源。
如本例中,如果在處理statement的異常時,拋出了,後面的conn資源就關閉不了了,所以採用try-catch是恰當的。

以上均爲個人分析,如有錯誤,還請指出,共同進步。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章