How to Use Rescue in One Line in Ruby: Simple Syntax and Examples
In Ruby, you can use
rescue in one line by placing it after an expression like expression rescue fallback_value. This catches exceptions from the expression and returns the fallback value without needing a full begin...rescue...end block.Syntax
The one-line rescue syntax in Ruby looks like this:
expression rescue fallback_value
Here, expression is the code that might raise an error.
rescue catches any exception from the expression.
fallback_value is returned if an error occurs.
ruby
result = 1 / 0 rescue "Cannot divide by zero" puts result
Output
Cannot divide by zero
Example
This example shows how to safely divide two numbers using one-line rescue. If division by zero happens, it returns a friendly message instead of crashing.
ruby
def safe_divide(a, b) a / b rescue "Error: division by zero" end puts safe_divide(10, 2) # Outputs 5 puts safe_divide(10, 0) # Outputs Error: division by zero
Output
5
Error: division by zero
Common Pitfalls
One-line rescue catches all StandardError exceptions, which can hide bugs if used carelessly.
It only rescues exceptions from the expression immediately before it, so complex expressions may not behave as expected.
Use it for simple cases, not for complex error handling.
ruby
puts (1 / 0) + 2 rescue "Rescued error" # Wrong: rescue only applies to the entire expression, but the addition happens after rescue # Correct way: puts (1 / 0 rescue "Rescued error") + 2
Output
Rescued error
2
Quick Reference
Tips for using one-line rescue:
- Use for simple expressions that might fail.
- Returns fallback value if error occurs.
- Does not catch exceptions outside the expression.
- Avoid hiding bugs by rescuing too broadly.
Key Takeaways
Use one-line rescue as: expression rescue fallback_value to handle errors simply.
It catches exceptions only from the expression immediately before rescue.
Avoid using it for complex error handling to prevent hiding bugs.
One-line rescue returns the fallback value if an error occurs.
Use it for quick, simple error handling in expressions.