3

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

4

4 回答 4

8

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

begin
  exit
rescue SystemExit
end

puts "Still here!"

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

begin
  exit!
rescue SystemExit
end

puts "Didn't make it here :("
于 2012-03-04T00:13:45.097 回答
1

Edu already asked: If you want to abort the program, why not going straight for it and use 'exit'

One Possibility: You may define your own Exception and when the exception is called, the exception stopps the programm with 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 :("
于 2012-03-03T23:13:38.787 回答
0

My answer is similar to Maran's one, but slightly different:

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 :("
于 2012-03-03T23:13:45.513 回答
0

这会做你想要的吗?

begin
  puts Idontexist
rescue StandardError
  exit
  puts "You will never see meeeeeee!"
end
puts "I will never get called neither :("
于 2012-03-03T23:01:18.133 回答