如何在引发异常时中止Ruby脚本?

时间:2012-03-03 22:11:49

标签: ruby exception exception-handling rescue

在Ruby中,是否有可能引发一个异常,它也会自动中止程序,忽略任何封闭的开始/救援块?

4 个答案:

答案 0 :(得分:7)

不幸的是,这些exit答案都不起作用。 exit提出可以被抓住的SystemExit。观察:

begin
  exit
rescue SystemExit
end

puts "Still here!"

正如@dominikh所说,你需要使用exit!代替:

begin
  exit!
rescue SystemExit
end

puts "Didn't make it here :("

答案 1 :(得分:1)

Edu已经问过:如果你想中止该计划,为什么不直接使用它并使用'exit'

一种可能性: 您可以定义自己的Exception,并在调用异常时,异常将使用exit停止程序:

class MyException < StandardError
  #If this Exception is created, leave programm.
  def initialize
    exit 99
  end
end


begin
  raise MyException
rescue MyException
  puts "You will never see meeeeeee!"
end
puts "I will never get called neither :("

答案 2 :(得分:0)

这会做你想要的吗?

begin
  puts Idontexist
rescue StandardError
  exit
  puts "You will never see meeeeeee!"
end
puts "I will never get called neither :("

答案 3 :(得分:0)

我的答案与Maran的答案类似,但略有不同:

begin
  puts 'Hello'
  # here, instead of raising an Exception, just exit.
  exit
  puts "You will never see meeeeeee!"
rescue # whatever Exception
  # ...
end

puts "I will never get called neither :("