【发布时间】:2014-12-18 09:48:30
【问题描述】:
我一直在查看代码,并且已经看到尝试使用资源。我以前使用过标准的 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");
}
【问题讨论】:
-
不同之处在于您不需要在 try-wth-resource 中调用 stream.close()。如果您有一个关闭它的 finally 子句,它会自动调用。在 try-with-resouce 子句中只能使用实现 Closeable 或 AutoCloseable 的对象。
-
您不需要(或者很可能不应该)在
try{..}部分调用stream.close();。它应该在finally部分完成,try-with-resources 将为您处理(顺便说一句,try-with-resources 可以处理多个资源)。
标签: java try-catch try-with-resources