Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort a Ruby script when raising an Exception?

Is it possible, in Ruby, to raise an Exception that will also automatically abort the program, ignoring any enclosing begin/rescue blocks?

like image 840
user2398029 Avatar asked Sep 16 '25 22:09

user2398029


2 Answers

Unfortunately, none of these exit answers will work. exit raises SystemExit which can be caught. Observe:

begin
  exit
rescue SystemExit
end

puts "Still here!"

As @dominikh says, you need to use exit! instead:

begin
  exit!
rescue SystemExit
end

puts "Didn't make it here :("
like image 196
Lee Jarvis Avatar answered Sep 19 '25 15:09

Lee Jarvis


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

One Possibility: You may define your own Exception and when the exception is called, the exception stops the program with 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 :("
like image 29
knut Avatar answered Sep 19 '25 14:09

knut