亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試使用資源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條經驗 獲得超6個贊

你錯過了什么,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 關注
  • 409 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號