繁体   English   中英

如何在没有开始和结束块的情况下在 Ruby 中使用救援

[英]How does one use rescue in Ruby without the begin and end block

我知道开始救援结束的标准技术

如何单独使用救援块。

它是如何工作的以及它如何知道正在监视哪些代码?

方法“def”可以作为“begin”语句:

def foo
  ...
rescue
  ...
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
  # 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM