尝试使用资源与Try-Catch

com*_*est 31 java try-catch try-with-resources

我一直在看代码,我已经看过尝试资源.之前我使用过标准的try-catch语句,看起来它们做同样的事情.所以我的问题是Try With Resources vs 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");
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 47

try-with-resources的要点是确保资源被关闭,而不需要应用程序代码.但是,有一些更好的要点需要考虑.

当您不使用try-with-resources时,可能存在一个称为异常屏蔽的陷阱.当try块中的代码抛出异常,并且finally中的close方法也抛出异常时,try块抛出的异常会丢失,并且finally中抛出的异常会被传播.这通常是不幸的,因为关闭时抛出的异常是无益的,而有用的异常是信息性异常.使用try-with-resources关闭资源可以防止发生任何异常屏蔽.

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

使用try-with-resources,如果try块抛出异常并且close方法也抛出异常,则close块中的异常会被添加到原始异常:

...在某些情况下,可以在兄弟代码块中抛出两个独立的异常,特别是在try-with-resources语句的try块和编译器生成的finally块中,它关闭资源.在这些情况下,只能传播一个抛出的异常.在try-with-resources语句中,当存在两个此类异常时,将传播源自try块的异常,并将finally块中的异常添加到由try块中的异常抑制的异常列表中.作为异常展开堆栈,它可以累积多个抑制异常.

另一方面,如果您的代码正常完成但是您正在使用的资源在关闭时抛出异常,那么该异常(如果try块中的代码抛出任何东西就会被抑制)会被抛出.这意味着如果您有一些JDBC代码,其中ResultSet或PreparedStatement由try-with-resources关闭,则可以抛出JDBC对象关闭时由于某些基础结构故障导致的异常,并且可以回滚否则将成功完成的操作.

没有try-with-resources,是否抛出close方法异常取决于应用程序代码.如果在try块抛出异常时它被抛出finally块,则finally块中的异常将掩盖另一个异常.但是开发人员可以选择捕获关闭时抛出的异常,而不是传播它.


Ell*_*sch 5

你错过了什么,finally块.这try-with-resouces将使它像,

FileOutputStream outStream = null;
try {
  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");
} finally {
  if (outStream != null) { 
    try { 
      outStream.close(); 
    } catch (Exception e) {
    } 
  }
}
Run Code Online (Sandbox Code Playgroud)

这意味着你真的想要(从不吞下例外),

try (FileOutputStream outStream = new FileOutputStream("people.bin");
     ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
  stream.writeObject(jar);
  stream.writeObject(can);
  // stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
    System.out.println("sorry it didn't work out");
    e.printStackTrace();
} catch(IOException f) {
    System.out.println("sorry it didn't work out");
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)