ale*_*dev 215
方法"def"可以作为"开始"语句:
def foo
...
rescue
...
end
Run Code Online (Sandbox Code Playgroud)
pek*_*eku 48
你也可以内联救援:
1 + "str" rescue "EXCEPTION!"
Run Code Online (Sandbox Code Playgroud)
将打印出"EXCEPTION!" 因为'String不能强制进入Fixnum'
小智 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)
奖金!您也可以使用其他类型的块来执行此操作。例如:
[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)
| 归档时间: |
|
| 查看次数: |
32946 次 |
| 最近记录: |