Rescue NameError but not NoMethodError - ruby

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

Related

rescue that calls a method with a rescue

This only prints rescue 1, is there a way to print both rescue 1 and rescue 2?
def mimiti
raise 'hi there!'
rescue
puts 'rescue 1'
end
begin
mimiti
rescue
puts 'rescue 2'
end
Yes, you can re-raise an exception after catching and handling it:
def mimiti
raise 'hi there!'
rescue StandardError => e
puts 'rescue 1'
raise e
end

How to get the reference alive to the older one, when there is a second exception in Ruby?

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

Error handling: How to throw/catch errors correctly

I have a method that calls two other methods:
def first_method
second_method
# Don´t call this method when something went wrong before
third_method
end
The second_method calls other methods:
def second_method
fourth_method
fifth_method
end
Let´s say the fifth_method has a begin/rescue statement:
def fifth_method
begin
# do_something
rescue Error => e
#
end
end
Now I want to avoid third_method to be called when fifth_method throws an error. How would I/you solve this most elegantly in Ruby.
It seems to me so obvious but anyway
def first_method
begin
second_method
rescue
return
end
third_method
end
This construction (without explicit type of exception) will catch StandartError exception.
To avoid intersection with another exceptions you can create your own exception class:
class MyError < StandardError; end
and then use it
begin
second_method
rescue MyError => e
return
end
Note that you should not inherit exception from Exception because this type of exceptions are from environment level, where the exceptions of StandardError are meant to deal with application level errors.
I think the simplest way is removing error catching from fifth_method and move it to the first_method
def first_method
begin
second_method
third_method
rescue Error => e
end
end
def fifth_method
# do_something
end
If you don't want to use exceptions, you can just return a status:
def fifth_method
# do_something
true
rescue Error => e
false
end
def first_method
if second_method
third_method
end
end

Is SystemExit a special kind of Exception?

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]

How does one use rescue in Ruby without the begin and end block

I know of the standard technique of having a begin rescue end
How does one just use the rescue block on its own.
How does it work and how does it know which code is being monitored?
A method "def" can serve as a "begin" statement:
def foo
...
rescue
...
end
You can also rescue inline:
1 + "str" rescue "EXCEPTION!"
will print out "EXCEPTION!" since 'String can't be coerced into Fixnum'
I'm using the def / rescue combination a lot with ActiveRecord validations:
def create
#person = Person.new(params[:person])
#person.save!
redirect_to #person
rescue ActiveRecord::RecordInvalid
render :action => :new
end
I think this is very lean code!
Example:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end
Here, def as a begin statement:
def
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end
Bonus! You can also do this with other sorts of blocks. E.g.:
[1, 2, 3].each do |i|
if i == 2
raise
else
puts i
end
rescue
puts 'got an exception'
end
Outputs this in irb:
1
got an exception
3
=> [1, 2, 3]

Resources