Recall & Review
beginner
What is the rescue modifier (inline form) in Ruby?
It is a way to handle exceptions in a single line using the
rescue keyword after an expression. It returns the expression's value if no error occurs, or the rescue value if an error happens.Click to reveal answer
beginner
How does the rescue modifier differ from a full
begin-rescue-end block?The rescue modifier is shorter and used inline after an expression, while
begin-rescue-end is a block that can handle multiple lines and more complex error handling.Click to reveal answer
beginner
Example: What does
result = 10 / 0 rescue 'error' return?It returns the string
'error' because dividing by zero raises an exception, which is caught by the rescue modifier.Click to reveal answer
intermediate
Can the rescue modifier catch specific exception types?
No, the rescue modifier catches all StandardError exceptions by default. For specific exceptions, use a full
begin-rescue block.Click to reveal answer
beginner
Why use the rescue modifier instead of a full rescue block?
It makes code shorter and cleaner for simple error handling when you want to provide a fallback value quickly.
Click to reveal answer
What does the rescue modifier do in Ruby?
✗ Incorrect
The rescue modifier catches exceptions inline and returns the fallback value if an error happens.
Which of these is a correct use of the rescue modifier?
✗ Incorrect
The rescue modifier is used after an expression, like
value = 5 / 0 rescue 'fail'.If no error occurs, what does the rescue modifier return?
✗ Incorrect
If no error happens, the rescue modifier returns the original expression's value.
Can the rescue modifier specify which exception to catch?
✗ Incorrect
The rescue modifier catches all StandardError exceptions by default; specific exceptions require a full rescue block.
Which is a benefit of using the rescue modifier?
✗ Incorrect
The rescue modifier makes code shorter and cleaner for simple fallback values.
Explain how the rescue modifier works in Ruby and when you might use it.
Think about how to handle errors quickly in one line.
You got /4 concepts.
Write a Ruby expression using the rescue modifier to divide two numbers and return 'error' if division fails.
Use the rescue keyword after the division.
You got /3 concepts.