【问题标题】:Unable to catch an exception in Ruby无法在 Ruby 中捕获异常
【发布时间】:2009-08-11 00:22:08
【问题描述】:

我有这样的事情:

class Vehicle

  def self.set_color(input)
     if %w{blue red green}.include?(input)
       input
     else
       raise "Bad color"
     end
  end

end

class Car < Vehicle

   def make_car
      begin
        my_color = Vehicle.set_color("orange")
      rescue
        puts "you screwed the pooch"
      end
   end

end

class CarTest < Test::Unit::TestCase
   def test_number_one
     c = Car.new
     c.make_car
   end
end

但由于某种原因,我的测试是引发异常并停止执行,而不是捕获它并输出“你搞砸了狗”。知道为什么会发生这种情况以及如何解决吗?

谢谢!

【问题讨论】:

  • 如果你在 TestCase 之外执行c.make_car 会发生这种情况吗?它对我来说应该输出“你把狗搞砸了”..

标签: ruby exception-handling


【解决方案1】:

没有参数的救援不是“包罗万象”的例外。

如果你只是发出一个“救援”,它只会救援一个 StandardError 异常(它将捕获一个 RuntimeError

如果你真的想抓住一切,你应该做一个


rescue Exception

【讨论】:

【解决方案2】:

我 99% 确定“in”是 ruby​​ 中的受保护关键字。尝试使用不同的变量名。

【讨论】:

  • 就是这样; for i in some_collection (...)
  • 上面的代码不是确切的代码,只是简单到足以证明这个想法的代码。我不在实际程序中使用“in”,所以这不是问题。我编辑了帖子以反映这一点
猜你喜欢
  • 1970-01-01
  • 2021-08-19
  • 2010-10-29
  • 1970-01-01
  • 2021-08-07
  • 2021-10-14
  • 2019-11-27
  • 2014-05-02
相关资源
最近更新 更多