[英]How does one use rescue in Ruby without the begin and end block
I know of the standard technique of having a begin rescue end我知道开始救援结束的标准技术
How does one just use the rescue block on its own.如何单独使用救援块。
How does it work and how does it know which code is being monitored?它是如何工作的以及它如何知道正在监视哪些代码?
A method "def" can serve as a "begin" statement:方法“def”可以作为“begin”语句:
def foo
...
rescue
...
end
You can also rescue inline:您还可以内联救援:
1 + "str" rescue "EXCEPTION!"
will print out "EXCEPTION!"将打印出“例外!” since 'String can't be coerced into Fixnum'因为“字符串不能被强制转换为 Fixnum”
I'm using the def / rescue combination a lot with ActiveRecord validations:我在 ActiveRecord 验证中经常使用 def/rescue 组合:
def create
@person = Person.new(params[:person])
@person.save!
redirect_to @person
rescue ActiveRecord::RecordInvalid
render :action => :new
end
I think this is very lean code!我认为这是非常精简的代码!
Example:例子:
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
Here, def
as a begin
statement:在这里, 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
Bonus!奖金! You can also do this with other sorts of blocks.您也可以使用其他类型的块来执行此操作。 Eg:例如:
[1, 2, 3].each do |i|
if i == 2
raise
else
puts i
end
rescue
puts 'got an exception'
end
Outputs this in irb
:在irb
输出:
1
got an exception
3
=> [1, 2, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.