在没有开始和end块的Ruby中如何使用rescue

s4chpxco  于 2023-05-28  发布在  Ruby
关注(0)|答案(5)|浏览(148)

我知道使用begin <some code> rescue <rescue code> end的标准技术
如何单独使用rescue块?
它是如何工作的,以及它如何知道哪些代码正在被监视?

dm7nw8vv

dm7nw8vv1#

方法“def”可以用作“开始”语句:

def foo
  ...
rescue
  ...
end
nom7f22z

nom7f22z2#

您也可以在线救援:
将打印出“例外!“since 'String can't be coerced into Fixnum'

bwntbbo3

bwntbbo33#

我在ActiveRecord验证中经常使用def / rescue组合:

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

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

ktecyv1j

ktecyv1j4#

示例:

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
oiopk7p5

oiopk7p55#

奖励!你也可以用其他类型的块来做这个。例如:

[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]

相关问题