0

我有以下代码:

begin
   @output_file = File.open("output.txt", "w")
   File.read(@input_file).each_line do |line|
   taxify_line(line)
end
rescue => e
   p "Smz went wrong..."
end
@output_file.write("Last line of output")
@output_file.close unless @output_file.nil?

确保无论我捕获异常,两个文件(@input_file 和@output_file)都关闭的正确方法是什么?

4

1 回答 1

6

rescue子句应该在 begin..end 块内。还有,令人惊讶的是,ensure子句完全符合您的想法

begin
   @output_file = File.open("output.txt", "w")
   File.read(@input_file).each_line do |line|
     taxify_line(line)
   end
rescue => e
   p "Smz went wrong..."
ensure
  @output_file.write("Last line of output")
  @output_file.close unless @output_file.nil?
end
于 2012-11-01T11:43:48.583 回答