如何在抛出Exception时中止Ruby脚本?

m1m5dgzv  于 2023-10-18  发布在  Ruby
关注(0)|答案(4)|浏览(100)

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

vbopmzt1

vbopmzt11#

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

begin
  exit
rescue SystemExit
end

puts "Still here!"

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

begin
  exit!
rescue SystemExit
end

puts "Didn't make it here :("
e7arh2l6

e7arh2l62#

埃杜已经问过了:* 如果你想中止程序,为什么不直接使用“退出”*
一种可能:你可以定义自己的Exception,当异常被调用时,异常会通过exit停止程序:

class MyException < StandardError
  #If this Exception is created, leave program.
  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 :("
9njqaruj

9njqaruj3#

这能满足你的要求吗

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

zynd9foi4#

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

相关问题