【发布时间】:2010-12-05 06:53:55
【问题描述】:
我知道开始救援结束的标准技巧
如何单独使用救援块。
它是如何工作的,它如何知道正在监控哪些代码?
【问题讨论】:
标签: ruby
我知道开始救援结束的标准技巧
如何单独使用救援块。
它是如何工作的,它如何知道正在监控哪些代码?
【问题讨论】:
标签: ruby
方法“def”可以用作“开始”语句:
def foo
...
rescue
...
end
【讨论】:
do/end 块字面量构成隐式异常块。
rescue TypeError; rescue NameError - 或者您可以用逗号分隔异常类,例如rescue TypeError, NameError
你也可以救援内联:
1 + "str" rescue "EXCEPTION!"
将打印出“例外!”因为 'String 不能被强制转换为 Fixnum'
【讨论】:
StandardError 及其所有子类,例如NameError——这意味着即使代码中的拼写错误也不会引发错误。请参阅@987654321 @.
我在 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
# 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]
【讨论】: