0
0
Rubyprogramming~5 mins

Rescue modifier (inline form) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AHandles exceptions inline and returns a fallback value if an error occurs
BDefines a new method
CCreates a loop
DDeclares a variable
Which of these is a correct use of the rescue modifier?
Arescue value = 5 / 0 'fail'
Bvalue = 5 / 0 rescue 'fail'
Cbegin value = 5 / 0 rescue 'fail' end
Dvalue = rescue 5 / 0 'fail'
If no error occurs, what does the rescue modifier return?
AThe original expression's value
BThe rescue value
Cnil
DAn error message
Can the rescue modifier specify which exception to catch?
ANo, it catches all exceptions including system errors
BYes, by adding the exception name after rescue
CYes, by using a block
DNo, it catches all StandardError exceptions
Which is a benefit of using the rescue modifier?
AHandles multiple exceptions separately
BAllows retrying the code automatically
CShorter code for simple error handling
DLogs errors to a file
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.