如何在Ruby中使用rescue而不使用begin和end块
我知道开始救援的标准方法 一个人如何独自使用救援模块 它是如何工作的,以及它如何知道正在监视哪个代码?方法“def”可以用作“begin”语句:如何在Ruby中使用rescue而不使用begin和end块,ruby,Ruby,我知道开始救援的标准方法 一个人如何独自使用救援模块 它是如何工作的,以及它如何知道正在监视哪个代码?方法“def”可以用作“begin”语句: def foo ... rescue ... end def # something which might raise an exception rescue SomeExceptionClass => some_variable # code that deals with some exception ensure #
def foo
...
rescue
...
end
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
您还可以在线救援:
1 + "str" rescue "EXCEPTION!"
将打印“异常!”,因为“字符串不能强制为Fixnum”我在ActiveRecord验证中经常使用def/rescue组合:
def create
@person = Person.new(params[:person])
@person.save!
redirect_to @person
rescue ActiveRecord::RecordInvalid
render :action => :new
end
我认为这是非常精简的代码 示例:
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
这里,def
作为begin
语句:
def foo
...
rescue
...
end
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
奖金!您也可以使用其他类型的块来执行此操作。例如:
[1, 2, 3].each do |i|
if i == 2
raise
else
puts i
end
rescue
puts 'got an exception'
end
在irb
中输出该值:
1
got an exception
3
=> [1, 2, 3]
此外,类定义、模块定义和(我认为)
do
/end
块文本构成隐式异常块。您也可以执行def rescue SECURE end吗?您完全可以执行def rescue SECURE end:-)您可以在def中使用多个rescue吗?@marriedjane875是的,您可以使用多个rescue,也可以显式执行(各救援条款/区块各自的线路)类似于rescue TypeError;rescue NAME ERROR
——或者您可以用逗号分隔异常类,例如rescue TypeError,NAME ERROR
如何解救并内联显示异常回溯?如何返回实际异常?内联解救不是一个好的做法,因为它解救StandardError
及其所有子类keNameError
–这意味着即使代码中的输入错误也不会引发错误。请参阅。