我最近開始使用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

HUWWW
TA貢獻1874條經驗 獲得超12個贊
如果要確保關閉文件,則應使用以下塊形式File.open:
File.open("myFile.txt", "w") do |file|
begin
file << "#{content} \n"
rescue
#handle the error here
end
end
- 3 回答
- 0 關注
- 620 瀏覽
添加回答
舉報
0/150
提交
取消