尝试使用资源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");

}


慕妹3146593
浏览 381回答 3
3回答

杨魅力

你错过了什么,finally街区。在try-with-resouces将使它像,FileOutputStream outStream = null;try {&nbsp; outStream = new FileOutputStream("people.bin");&nbsp; ObjectOutputStream stream = new ObjectOutputStream(outStream);&nbsp; stream.writeObject(jar);&nbsp; stream.writeObject(can);&nbsp; stream.close();} catch(FileNotFoundException e) {&nbsp; &nbsp; System.out.println("sorry it didn't work out");} catch(IOException f) {&nbsp; &nbsp; System.out.println("sorry it didn't work out");} finally {&nbsp; if (outStream != null) {&nbsp;&nbsp; &nbsp; try {&nbsp;&nbsp; &nbsp; &nbsp; outStream.close();&nbsp;&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; }&nbsp;&nbsp; }}这意味着您确实想要这样的东西(永远不要吞下异常),try (FileOutputStream outStream = new FileOutputStream("people.bin");&nbsp; &nbsp; &nbsp;ObjectOutputStream stream = new ObjectOutputStream(outStream);) {&nbsp; stream.writeObject(jar);&nbsp; stream.writeObject(can);&nbsp; // stream.close(); // <-- closed by try-with-resources.} catch(FileNotFoundException e) {&nbsp; &nbsp; System.out.println("sorry it didn't work out");&nbsp; &nbsp; e.printStackTrace();} catch(IOException f) {&nbsp; &nbsp; System.out.println("sorry it didn't work out");&nbsp; &nbsp; e.printStackTrace();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java