【问题标题】:How does one use rescue in Ruby without the begin and end block在没有开始和结束块的情况下如何在 Ruby 中使用救援
【发布时间】:2010-12-05 06:53:55
【问题描述】:

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

如何单独使用救援块。

它是如何工作的,它如何知道正在监控哪些代码?

【问题讨论】:

标签: ruby


【解决方案1】:

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

def foo
  ...
rescue
  ...
end

【讨论】:

  • 此外,类定义、模块定义和(我认为)do/end 块字面量构成隐式异常块。
  • 你也可以做 def rescue ensure end 吗?
  • 你也绝对可以做 def rescue ensure end :-)
  • 你能在你的 def 中使用多个救援吗?
  • @marriedjane875 是的,您可以使用多个救援,或者显式(每个救援子句/块在其自己的行上),如rescue TypeError; rescue NameError - 或者您可以用逗号分隔异常类,例如rescue TypeError, NameError
【解决方案2】:

你也可以救援内联:

1 + "str" rescue "EXCEPTION!"

将打印出“例外!”因为 'String 不能被强制转换为 Fixnum'

【讨论】:

  • 你如何拯救和显示异常回溯内联?
  • 如何返回实际异常?
  • 内联救援不是一个好习惯,因为它救援StandardError 及其所有子类,例如NameError——这意味着即使代码中的拼写错误也不会引发错误。请参阅@987654321 @.
【解决方案3】:

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

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

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

【讨论】:

    【解决方案4】:

    例子:

    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
    

    【讨论】:

      【解决方案5】:

      奖金!您也可以使用其他类型的块来执行此操作。例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-29
        • 2013-04-18
        • 2013-11-26
        相关资源
        最近更新 更多