我最近開始用Ruby編程,我正在研究異常處理。 編程
我想知道是否ensure
是finally
在C#中的Ruby等價物? 我應該: less
file = File.open("myFile.txt", "w") begin file << "#{content} \n" rescue #handle the error here ensure file.close unless file.nil? end
或者我應該這樣作? spa
#store the file file = File.open("myFile.txt", "w") begin file << "#{content} \n" file.close rescue #handle the error here ensure file.close unless file.nil? end
ensure
不管如何都被調用,即便沒有引起異常? code
僅供參考,即便在rescue
部分從新引起異常,也會在代碼執行繼續執行下一個異常處理程序以前執行ensure
阻止。 例如: 資源
begin raise "Error!!" rescue puts "test1" raise # Reraise exception ensure puts "Ensure block" end
這就是咱們須要ensure
: get
def hoge begin raise rescue raise # raise again ensure puts 'ensure' # will be executed end puts 'end of func' # never be executed end
是的, ensure
在任何狀況下都被調用。 有關更多信息,請參閱編程Ruby書籍的「 異常,捕獲和拋出 」並搜索「確保」。 io
若是要確保文件已關閉,則應使用File.open
的塊形式: test
File.open("myFile.txt", "w") do |file| begin file << "#{content} \n" rescue #handle the error here end end
是的, ensure
finally
保證塊將被執行 。 這對於確保關鍵資源受到保護很是有用,例如在出錯時關閉文件句柄或釋放互斥鎖。 書籍