Concept Flow - Rescue modifier (inline form)
Try expression
Success?
Yes→Return value
No
Rescue exception
Return rescue value
The rescue modifier tries to run an expression and if an error happens, it returns a fallback value instead.
result = 10 / 0 rescue "Error" puts result
| Step | Expression | Error Raised? | Rescue Triggered? | Result |
|---|---|---|---|---|
| 1 | 10 / 0 | Yes (ZeroDivisionError) | Yes | "Error" assigned to result |
| 2 | puts result | No | No | Prints: Error |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| result | nil | "Error" | "Error" |
rescue modifier syntax: expression rescue fallback_value Runs expression; if error occurs, returns fallback_value instead. Only rescues StandardError and subclasses. Useful for short error handling inline. Example: x = 1/0 rescue "fail"
value = 10 / x rescue 0?10 / x raises an error (like division by zero), the rescue modifier returns 0 instead of crashing.expression rescue fallback.result = some_method rescue fallback_value.value = Integer('abc') rescue 'error'
puts valueInteger('abc') raises an ArgumentError because 'abc' is not a valid number.result = 10 / 0 rescue puts 'Error!'
puts 'Error!', which prints the message.puts returns nil, so result is assigned nil after rescue.Integer(user_input) and returns -1 on failure.Pass the test and this pattern moves unknown