在Ruby中開始,拯救和確保?

我最近開始用Ruby編程,我正在研究異常處理。 編程

我想知道是否ensurefinally在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


#1樓

僅供參考,即便在rescue部分從新引起異常,也會在代碼執行繼續執行下一個異常處理程序以前執行ensure阻止。 例如: 資源

begin
  raise "Error!!"
rescue
  puts "test1"
  raise # Reraise exception
ensure
  puts "Ensure block"
end

#2樓

這就是咱們須要ensureget

def hoge
  begin
    raise
  rescue  
    raise # raise again
  ensure  
    puts 'ensure' # will be executed
  end  
  puts 'end of func' # never be executed
end

#3樓

是的, ensure在任何狀況下都被調用。 有關更多信息,請參閱編程Ruby書籍的「 異常,捕獲和拋出 」並搜索「確保」。 io


#4樓

若是要確保文件已關閉,則應使用File.open的塊形式: test

File.open("myFile.txt", "w") do |file|
  begin
    file << "#{content} \n"
  rescue
  #handle the error here
  end
end

#5樓

是的, ensure finally 保證塊將被執行 。 這對於確保關鍵資源受到保護很是有用,例如在出錯時關閉文件句柄或釋放互斥鎖。 書籍

相關文章
相關標籤/搜索