Is it possible, in Ruby, to raise an Exception that will also automatically abort the program, ignoring any enclosing begin/rescue blocks?
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 :("
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 :("
Would this do what you want?
begin
puts Idontexist
rescue StandardError
exit
puts "You will never see meeeeeee!"
end
puts "I will never get called neither :("
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 :("
Related
This simple test mostly results as
(1) rescue break, m.locked?: false
but sometimes I can see
(1) rescue break, m.locked?: true
m = Mutex.new
6.times do
Thread.new do
begin
m.synchronize do
puts 't1 action'
3.times do
puts '.'
sleep 0.5
end
raise 'Break'
end
rescue
puts "(1) rescue break, m.locked?: #{m.locked?}"
m.synchronize do
sleep 0.1
end
puts '(2) after m {sleep}'
sleep 0.1
puts 'rescue break 2'
end
end
sleep 0.1
t2 = Thread.new do
puts 't2 waiting for mutex'
m.synchronize do
puts '(3) t2 action'
end
end
t2.join
sleep 0.2
puts;puts;
end
I expected that inside the rescue block mutex will be always unlocked.
Environment:
Ruby v2.6.3.62 (2019-04-16) [x64-mingw32]
Nobody promised that the processor would stop the world, waiting for your action :) That said, between
raise 'Break'
and
puts "(1) rescue break, m.locked?: #{m.locked?}"
there is another thread that might get the execution time and in turn lock the mutex.
Please also note, that
raise 'Break'
end
rescue
puts "(1) rescue break, m.locked?: #{m.locked?}"
is effectively the same as
end
puts "(1) rescue break, m.locked?: #{m.locked?}"
In the latter snippet, it should be clear that m might be either locked by another thread, or not; we have it just released, so no promise.
I need to catch a NameError in a special case. But I don't want to catch all SubClasses of NameError. Is there a way to achieve this?
# This shall be catched
begin
String::NotExistend.new
rescue NameError
puts 'Will do something with this error'
end
# This shall not be catched
begin
# Will raise a NoMethodError but I don't want this Error to be catched
String.myattribute = 'value'
rescue NameError
puts 'Should never be called'
end
You can also do it in a more traditional way
begin
# your code goes here
rescue NoMethodError
raise
rescue NameError
puts 'Will do something with this error'
end
You can re-raise exception if its class is different than a given:
begin
# your code goes here
rescue NameError => exception
# note that `exception.kind_of?` will not work as expected here
raise unless exception.class.eql?(NameError)
# handle `NameError` exception here
end
You can also check the exception message and decide what to do.
Here is an example using the code you provided.
# This shall be catched
begin
String::NotExistend.new
rescue NameError => e
if e.message['String::NotExistend']
puts 'Will do something with this error'
else
raise
end
end
# This shall not be catched
begin
# Will raise a NoMethodError but I don't want this Error to be catched
String.myattribute = 'value'
rescue NameError => e
if e.message['String::NotExistend']
puts 'Should never be called'
else
raise
end
end
begin
raise "explosion"
rescue
p $!
raise "Are you mad"
p $!
end
# #<RuntimeError: explosion>
# RuntimeError: Are you mad
# from (irb):5:in `rescue in irb_binding'
# from (irb):1
# from /usr/bin/irb:12:in `<main>'
$! always holds only the current exception object reference.
But is there any way to get a reference to the original exception object (here it is "explosion"), after another exception has been raised? <~~~ Here is my question.
Myself tried and reached to the answer,hope now it is more clearer to all who was in Smokey situation with my queries.
Are you saying you want to have reference to the original exception when you rescue the second exception? If so, then you need to capture the original exception in a variable during the rescue. This is done by doing:
rescue StandardError => e
where StandardError can be any type of exception or omitted (in which case StandardError is the default).
For example, the code:
begin
raise "original exception"
rescue StandardError => e
puts "Original Exception:"
puts $!
puts e
begin
raise "second exception"
rescue
puts "Second Exception:"
puts $!
puts e
end
end
Gives the output:
Original Exception:
original exception
original exception
Second Exception:
second exception
original exception
As you can see e has stored the original exception for use after the second exception.
class MyError < StandardError
attr_reader :original
def initialize(msg, original=$!)
super(msg)
#original = original;
end
end
begin
begin
raise "explosion"
rescue => error
raise MyError, "Are you mad"
end
rescue => error
puts "Current failure: #{error.inspect}"
puts "Original failure: #{error.original.inspect}"
end
OUTPUT
Current failure: #<MyError: Are you mad>
Original failure: #<RuntimeError: explosion>
=> nil
How does SystemExit behave differently from other Exceptions? I think I understand some of the reasoning about why it wouldn't be good to raise a proper Exception. For example, you wouldn't want something strange like this to happen:
begin
exit
rescue => e
# Silently swallow up the exception and don't exit
end
But how does the rescue ignore SystemExit? (What criteria does it use?)
When you write rescue without one or more classes, it is the same as writing:
begin
...
rescue StandardError => e
...
end
There are Exceptions that do not inherit from StandardError, however. SystemExit is one of these, and so it is not captured. Here is a subset of the hierarchy in Ruby 1.9.2, which you can find out yourself:
BasicObject
Exception
NoMemoryError
ScriptError
LoadError
Gem::LoadError
NotImplementedError
SyntaxError
SecurityError
SignalException
Interrupt
StandardError
ArgumentError
EncodingError
Encoding::CompatibilityError
Encoding::ConverterNotFoundError
Encoding::InvalidByteSequenceError
Encoding::UndefinedConversionError
FiberError
IOError
EOFError
IndexError
KeyError
StopIteration
LocalJumpError
NameError
NoMethodError
RangeError
FloatDomainError
RegexpError
RuntimeError
SystemCallError
ThreadError
TypeError
ZeroDivisionError
SystemExit
SystemStackError
fatal
You can thus capture just SystemExit with:
begin
...
rescue SystemExit => e
...
end
...or you can choose to capture every exception, including SystemExit with:
begin
...
rescue Exception => e
...
end
Try it yourself:
begin
exit 42
puts "No no no!"
rescue Exception => e
puts "Nice try, buddy."
end
puts "And on we run..."
#=> "Nice try, buddy."
#=> "And on we run..."
Note that this example will not work in (some versions of?) IRB, which supplies its own exit method that masks the normal Object#exit.
In 1.8.7:
method :exit
#=> #<Method: Object(IRB::ExtendCommandBundle)#exit>
In 1.9.3:
method :exit
#=> #<Method: main.irb_exit>
Simple example:
begin
exit
puts "never get here"
rescue SystemExit
puts "rescued a SystemExit exception"
end
puts "after begin block"
The exit status / success?, etc. can be read too:
begin
exit 1
rescue SystemExit => e
puts "Success? #{e.success?}" # Success? false
end
begin
exit
rescue SystemExit => e
puts "Success? #{e.success?}" # Success? true
end
Full list of methods: [:status, :success?, :exception, :message, :backtrace, :backtrace_locations, :set_backtrace, :cause]
I'm looking for something like this:
raise Exception rescue nil
But the shortest way I've found is this:
begin
raise Exception
rescue Exception
end
This is provided by ActiveSupport:
suppress(Exception) do
# dangerous code here
end
http://api.rubyonrails.org/classes/Kernel.html#method-i-suppress
def ignore_exception
begin
yield
rescue Exception
end
end
Now write you code as
ignore_exception { puts "Ignoring Exception"; raise Exception; puts "This is Ignored" }
Just wrap the left-hand side in parenthesis:
(raise RuntimeError, "foo") rescue 'yahoo'
Note that the rescue will only happen if the exception is a StandardError or a subclass thereof. See http://ruby.runpaint.org/exceptions for more info.