异常处理

begin...rescue...ensure...end

begin...end 块可以弥补部分代码中的不足。它通常用于异常处理。

begin
  puts "a bare begin/end alone isn't terribly useful'
end
begin
  puts "however when used with a rescue, exception handling results"
  raise Exception.new("my exception")
rescue Exception => e
  puts e.backtrace
end

begin...end 块既可以单独使用,也可以与一个或多个 rescue 块和/或 ensure 块一起使用。

begin
  puts "ensure blocks are useful for cleaning up resources regardless of errors that may occur"
  f = File.open("myfile")
  raise Exception.new
rescue NameError => n
  # no NameError raised, so we'll not get here
ensure
  # but we'll always get here, unless the interpreter or thread terminates
  f.close
end

请注意,Ruby 的局部变量标准作用域也适用 begin...end 块:给定方法中只有一个作用域(不包括块作用域的变量)。

匿名形式的 rescue 仅捕获 StandardError 导致的异常,如下所示:

begin
  eval "\"" # raises a SyntaxError
rescue => e
  # The SyntaxError will not be caught
end

请与下面的语句进行比较:

begin
  raise NameError.new("Some name error")
rescue => e
  # The NameError will be caught
end