How does `rescue $!` Work?

I know that a global variable $!contains the most recent exception object, but I am confused with the syntax below. Can someone help me understand the following syntax?

 rescue $!
+5
source share
1 answer

This design prevents exclusion from your program and bubbling of the stack trace. It also returns this exception as a value that may be useful.

a = get_me_data rescue $!

After this line it awill contain either the requested data or an exception. You can then parse this 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 $!

, ( , ..). .

+9

All Articles