Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `rescue $!` work?

I know that the global variable $! holds the most recent exception object, but I am having confusion with the syntax below. Can anyone help me understand the following syntax?

 rescue $!
like image 818
arun_roy Avatar asked Feb 09 '13 10:02

arun_roy


1 Answers

This construct prevents exception from stopping your program and bubbling up the stack trace. It also returns that exception as a value, which can be useful.

a = get_me_data rescue $!

After this line, a will hold either requested data or an exception. You can then analyze that exception and act accordingly.

def get_me_data
  raise 'No data for you'
end

a = get_me_data rescue $!
puts "Execution carries on"

p a
# >> Execution carries on
# >> #<RuntimeError: No data for you>

More realistic example

lines = File.readlines(filename) rescue $!

You either get the lines or the error (if file doesn't exist, you don't have permissions, etc). In any case, execution doesn't stop.

like image 113
Sergio Tulentsev Avatar answered Oct 17 '22 06:10

Sergio Tulentsev