begin
raise 'foo'
rescue
puts $!.inspect # => #<RuntimeError: foo>
ensure
puts $!.inspect # => nil
end
puts $!.inspect # => nil
Googled around but didn't find a clear answer.
Just want to confirm the life-time(?) of $!
, does it hold value only inside a rescue
block?
For each rescue clause, the raised Ruby exception is compared against each parameter and the match succeeds if the exception in the clause is the same as or a superclass of the thrown exception. If the thrown Ruby exception does not match any of the specified exception types, the else block gets executed.
Ruby Internal try catch (raise and rescue) In case exceptions happen in the begin block it will halt and control will go between rescue and end, and we can return a valid message for the user in case of exceptions. Every time for a rescue statement Ruby checks and compares the exception raised for each parameter.
Rescuing Exceptions is not idiomatic We don't want to rescue Exception s, however. Exceptions that aren't StandardError s are reserved for things like Interrupt when we hit Ctrl-C, and NoMemoryError . Exceptions that are StandardError s are what a normal Ruby program are supposed to use.
$!
has the error in the rescue block, or in the the ensure block if there's no rescue block:
begin
raise 'foo'
ensure
puts $!.inspect # => #<RuntimeError: foo>
end
$!
has the value nil
everywhere else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With