java - Try With Resources 与 Try-Catch

标签 java try-catch try-with-resources

我一直在查看代码,并且已经看到了对资源的尝试。我以前使用过标准的 try-catch 语句,看起来它们做了同样的事情。所以我的问题是 Try With Resources 与 Try-Catch 它们之间有什么区别,哪个更好。

这是对资源的尝试:

objects jar = new objects("brand");
objects can= new objects("brand");

try (FileOutputStream outStream = new FileOutputStream("people.bin")){
    ObjectOutputStream stream = new ObjectOutputStream(outStream);

    stream.writeObject(jar);
    stream.writeObject(can);

    stream.close();
} catch(FileNotFoundException e) {
    System.out.println("sorry it didn't work out");
} catch(IOException f) {
    System.out.println("sorry it didn't work out");
}

最佳答案

try-with-resources 的要点是确保资源可靠地关闭,而不会丢失信息。

当您不使用 try-with-resources 时,存在一个潜在的陷阱,称为异常屏蔽。当try block 中的代码抛出异常,并且finally中的close方法也抛出异常时,try block 抛出的异常将丢失,而finally中抛出的异常将被传播。这通常是不幸的,因为关闭时抛出的异常是没有帮助的,而信息丰富的异常是从 try block 内抛出的异常。 (因此,您不会看到 SQLException 告诉您哪个引用完整性约束被违反,而是显示类似 BrokenPipeException 的内容,其中关闭资源失败。)

这种异常屏蔽是一个恼人的问题,try-with-resources 可以防止发生。

作为确保异常屏蔽不会丢失重要异常信息的一部分,当开发 try-with-resources 时,他们必须决定如何处理 close 方法抛出的异常。

使用 try-with-resources,如果 try block 抛出异常并且 close 方法也抛出异常,则 the exception from the close block gets tacked on to the original exception :

... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.

另一方面,如果您的代码正常完成,但您正在使用的资源在关闭时抛出异常,则该异常(如果 try block 中的代码抛出任何内容,该异常将被抑制)将被抛出。这意味着,如果您有一些 JDBC 代码,其中 ResultSet 或PreparedStatement 通过 try-with-resources 关闭,那么当 JDBC 对象关闭时,可能会引发因某些基础设施故障而导致的异常,并且可能会回滚本来会成功完成的操作.

如果没有 try-with-resources,是否抛出 close 方法异常取决于应用程序代码。如果当 try block 抛出异常时在 finally block 中抛出该异常,则来自 finally block 的异常将掩盖其他异常。但开发人员可以选择捕获关闭时引发的异常而不传播它。

关于java - Try With Resources 与 Try-Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316420/

相关文章:

java - 在启动时检索所有基本数据

java - JMeter - 无法使用 CIFS Sampler(Groovy) 扩展网络带宽

java - 在 Play 框架中将 Promise 列表转换为 List 的 Promise

c++ - MongoDB C++ 驱动程序不抛出连接错误

Python 3 异常 : TypeError: function missing 1 required positional argument: 'words'

java - 尝试资源失败但尝试有效

java - 在 Java 中尝试使用资源时出错

java - 在 MacOS X 上使用 Eclipse Mars 远程调试 Tomcat 7

python - 用python gtk键盘中断?

java - JVM堆不断增加。为什么?