为了账号安全,请及时绑定邮箱和手机立即绑定

尝试使用资源vs尝试捕获

尝试使用资源vs尝试捕获

慕妹3146593 2019-11-15 17:01:55
我一直在查看代码,并且已经尝试使用资源。我之前使用过标准的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");}
查看完整描述

3 回答

?
杨魅力

TA贡献1811条经验 获得超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) {

    } 

  }

}

这意味着您确实想要这样的东西(永远不要吞下异常),


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();

}


查看完整回答
反对 回复 2019-11-15
  • 3 回答
  • 0 关注
  • 350 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信