Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby's $! hold value only in rescue block?

Tags:

ruby

rescue

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?

like image 993
huocp Avatar asked Jan 09 '15 01:01

huocp


People also ask

How does rescue work in Ruby?

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.

Does Ruby have try catch?

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.

Is it bad to rescue exception?

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.


1 Answers

$! 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.

like image 165
joelparkerhenderson Avatar answered Sep 21 '22 07:09

joelparkerhenderson