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

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

開始,營救和確保使用Ruby?

開始,營救和確保使用Ruby?

滄海一幻覺 2019-11-21 10:34:02
我最近開始使用Ruby進行編程,并且正在研究異常處理。我想知道ensureRuby是否等效finally于C#?我應該有:file = File.open("myFile.txt", "w")begin  file << "#{content} \n"rescue  #handle the error hereensure  file.close unless file.nil?end還是我應該這樣做?#store the filefile = File.open("myFile.txt", "w")begin  file << "#{content} \n"  file.closerescue  #handle the error hereensure  file.close unless file.nil?end不會ensure得到所謂不管,即使一個異常沒有什么引發,?
查看完整描述

3 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

僅供參考,即使在本rescue節中再次引發了異常,ensure也會在代碼執行繼續到下一個異常處理程序之前執行該塊。例如:


begin

  raise "Error!!"

rescue

  puts "test1"

  raise # Reraise exception

ensure

  puts "Ensure block"

end


查看完整回答
反對 回復 2019-11-21
?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

如果要確保關閉文件,則應使用以下塊形式File.open:


File.open("myFile.txt", "w") do |file|

  begin

    file << "#{content} \n"

  rescue

  #handle the error here

  end

end


查看完整回答
反對 回復 2019-11-21
  • 3 回答
  • 0 關注
  • 620 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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