无法在Ruby中捕获异常

Ton*_*ony 2 ruby exception-handling

我有这样的事情:

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
Run Code Online (Sandbox Code Playgroud)

但出于某种原因,我的测试是提高异常并停止执行而不是捕获并输出"你搞砸了小狗".知道为什么会这样,以及如何解决它?

谢谢!

klo*_*ner 11

没有争论的救援不是例外的"全能".

如果您只是发出"救援",它只会挽救一个StandardError异常(它将捕获RuntimeError <StandardError),但不会引发异常.

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


rescue Exception
Run Code Online (Sandbox Code Playgroud)