【问题标题】:How to abort a Ruby script when raising an Exception?引发异常时如何中止 Ruby 脚本?
【发布时间】:2012-03-03 22:11:48
【问题描述】:

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

【问题讨论】:

标签: ruby exception exception-handling rescue


【解决方案1】:

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

begin
  exit
rescue SystemExit
end

puts "Still here!"

正如@dominikh 所说,您需要改用exit!

begin
  exit!
rescue SystemExit
end

puts "Didn't make it here :("

【讨论】:

  • 虽然与这个问题没有直接关系,但读者应该注意exit!也有没有处理at_exitEND块的副作用,在某些情况下可能会导致一些头部抓挠:-)
【解决方案2】:

Edu 已经问过:如果你想中止程序,为什么不直接使用'exit'

一种可能性: 您可以定义自己的异常,当异常被调用时,异常会通过 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 :("

【讨论】:

    【解决方案3】:

    这会做你想要的吗?

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

    【讨论】:

      【解决方案4】:

      我的回答与 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 :("
      

      【讨论】:

        猜你喜欢
        • 2019-08-04
        • 1970-01-01
        • 2018-12-21
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-27
        相关资源
        最近更新 更多