Rescue modifier
We can use rescue
modifier,
in inline mode to rescue from exceptions
raised by the RHS expression
and assign some value to variable.
num = 10
denominator = 0
result = num / denominator rescue 1 # evaluated as result = ((num/denominator) rescue 1)
=> 1
result
=> 1
Here, the RHS expression raises ZeroDivisionError
and rescue returns 1 in case of exception and
result
is assigned the value 1.
Rescue modifier with multiple assignments
Before Ruby 2.7, the expression is evaluated differently from single assignment mode in case of multiple assignments mode.
def calculate(num1, num2)
# calculation method raises an exception
raise StandardError
end
res1, res2 = calculate(1, 2) rescue [0, 0] # evaluated as (res1, res2 = raise) rescue [0, 0]
=> [0, 0]
res1
=> nil
res2
=> nil
With Ruby 2.7
This behaviour of rescue
modifier,
in case of multiple assignment was
fixed
and made consistent with the single assignment mode.
So now, the rescue is applied to the RHS.
def calculate(num1, num2)
# calculation method raises an exception
raise StandardError
end
res1, res2 = calculate(1, 2) rescue [0, 0] # evaluated as res1, res2 = (raise rescue [0, 0])
res1
=> 0
res2
=> 0