【发布时间】:2020-08-10 15:11:15
【问题描述】:
这是一种将新星球添加到可观察客户列表的方法。
我想知道我是否正确使用资源尝试以及自动关闭是否正常工作。
public static Customer addPlanet(Customer customer) {
String query1 = "Select * from planet where planet=? AND universeID=?";
String query2 = "INSERT INTO planet (planet,universeID) VALUES(?,?)";
try (PreparedStatement statement = (PreparedStatement) Database.connection.prepareStatement(query1);
PreparedStatement statement2 = (PreparedStatement) Database.connection.prepareStatement(query2)) {
statement.setString(1, customer.getPlanet());
statement.setString(2, Integer.toString(customer.getUniverseID()));
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
int planetId = rs.getInt(1);
customer.setPlanetID(planetId);
return customer;
} else {
statement2.setString(1, customer.getPlanet());
statement2.setInt(2, customer.getUniverseID());
statement2.executeUpdate();
return addPlanet(customer);
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return customer;
}
我的问题是,这部分需要包含在 try-catch 块中还是自动关闭。
statement2.executeUpdate();
【问题讨论】:
-
try没问题,但您应该删除catch块,这样您就不会像当前那样忽略异常。 -
抱歉,我是新手。是不是因为“打印异常的堆栈跟踪可能对调试有用,但结果程序执行相当于抑制异常。”?
-
既然您在外部
try语句中捕获了异常并继续,如果没有出现任何问题,即正常返回customer对象,那么是的,您忽略 异常,因为调用者无法知道addPlanet()调用失败。删除 2 个catch子句,并在方法中添加throws SQLException,这样调用者就会看到异常。在调用堆栈的某个位置,一个方法可能会打印堆栈跟踪。
标签: java try-catch try-with-resources