如何在没有开始和结束块的情况下在Ruby中使用rescue

Sid*_*Sid 111 ruby

我知道有一个开始救援结束的标准技术

如何单独使用救援区.

它是如何工作的以及它如何知道正在监视哪些代码?

ale*_*dev 215

方法"def"可以作为"开始"语句:

def foo
  ...
rescue
  ...
end
Run Code Online (Sandbox Code Playgroud)

  • 此外,类定义,模块定义和(我认为)`do` /`end`块文字形成隐式异常块. (3认同)

pek*_*eku 48

你也可以内联救援:

1 + "str" rescue "EXCEPTION!"
Run Code Online (Sandbox Code Playgroud)

将打印出"EXCEPTION!" 因为'String不能强制进入Fixnum'

  • 内联救援不是一个好的做法,因为它会救援 `StandardError` 及其所有子类,例如 `NameError` – 这意味着即使代码中存在拼写错误也不会引发错误。请参阅 https://thoughtbot.com/blog/不要在 ruby​​ 中内联救援。 (2认同)

小智 26

我通过ActiveRecord验证使用了def/rescue组合:

def create
   @person = Person.new(params[:person])
   @person.save!
   redirect_to @person
rescue ActiveRecord::RecordInvalid
   render :action => :new
end
Run Code Online (Sandbox Code Playgroud)

我认为这是非常精益的代码!


Hie*_* Le 19

例:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end
Run Code Online (Sandbox Code Playgroud)

在这里,def作为一个begin声明:

def
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end
Run Code Online (Sandbox Code Playgroud)


Pur*_*ket 5

奖金!您也可以使用其他类型的块来执行此操作。例如:

[1, 2, 3].each do |i|
  if i == 2
    raise
  else
    puts i
  end
rescue
  puts 'got an exception'
end
Run Code Online (Sandbox Code Playgroud)

输出如下irb

1
got an exception
3
 => [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)