我想在内部尝试中嵌套尝试捕获。
例如:
try (Connection conn = new Connection()) {
//Fill preparedStatement etc
try (ResultSet rs = conn.execute()){
}
} catch (SQLException e) {
//Log both exceptions here
}
这是可能的,这是一个好习惯吗?
您可以做到这一点:
try (Connection conn = new Connection()) {
ResultSet rs = conn.execute()
// do stuff with rs
} catch (SQLException e) {
// handle exception
}
conn.execute((抛出的例外将被捕获块捕获。新连接((抛出的例外将被抑制:
可以从与之关联的代码块中抛出一个例外 试用 - 资源语句。在示例中 writetofilezipfilectents,可以从尝试中抛出一个例外 块,最多可以从中抛出两个例外 试图关闭Zipfile时,请与Resources语句。 BufferedWriter对象。如果从尝试块抛出例外 从试用的资源抛出了一个或多个例外 声明,然后从try-with-resources中提出的那些例外 声明被抑制了,块抛出的例外是 由Writetofilezipfilecontents方法抛出的一种。你可以 通过调用 从试验抛出的例外 块。
请参阅:https://docs.oracle.com/javase/tutorial/essential/essential/expections/tryresourceclose.html
编辑:正如蒂莫西(Timothy(指出的那样,连接不能保证关闭其创建的结果集。所以我们需要这样的东西:
try (Connection conn = new Connection();
Statement statement = connection.createStatement()) {
// statement.set(....)
try (ResultSet rs = conn.execute()) {
// do stuff with rs
}
} catch (SQLException e) {
// handle exceptions
}
是的,但是更好的是
try (Connection conn = new Connection(); ResultSet rs = conn.execute();){
} catch (SQLException e) {
//Log both exceptions here
}