java try finally block to close stream

前端 未结 8 887
时光取名叫无心
时光取名叫无心 2020-12-05 17:25

I want to close my stream in the finally block, but it throws an IOException so it seems like I have to nest another try block in my finally<

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 17:49

    public void enumerateBar() throws SQLException {
        Statement statement = null;
        ResultSet resultSet = null;
        Connection connection = getConnection();
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM Bar");
            // Use resultSet
        }
        finally {
            try {
                if (resultSet != null)
                    resultSet.close();
            }
            finally {
                try {
                    if (statement != null)
                        statement.close();
                }
                finally {
                    connection.close();
                }
            }
        }
    }
    
    private Connection getConnection() {
        return null;
    }
    

    source. This sample was useful for me.

提交回复
热议问题