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