gpt4 book ai didi

java - 没有内部 catch block 的嵌套 try/catch

转载 作者:行者123 更新时间:2023-11-30 10:30:14 28 4
gpt4 key购买 nike

我想在内部 try 中嵌套一个 try catch 而没有 catch。
例如:

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() 抛出的异常将被 catch block 捕获。 new Connection() 抛出的异常将被抑制:

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

参见:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

编辑:正如 Timothy 所指出的,Connection 不保证关闭它创建的结果集。所以我们需要这样的东西:

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
}

关于java - 没有内部 catch block 的嵌套 try/catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739142/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com