Recall & Review
beginner
What is the purpose of the
ensure block in Ruby?The
ensure block runs code that must execute no matter what happens in the begin block, such as cleaning up resources or closing files.Click to reveal answer
beginner
How does
ensure differ from rescue in Ruby?rescue handles exceptions when they occur, while ensure always runs after begin, whether an exception happened or not.Click to reveal answer
intermediate
What happens if an exception is raised inside an
ensure block?If an exception occurs inside
ensure, it will override any previous exception and propagate up, potentially hiding the original error.Click to reveal answer
beginner
Why is
ensure useful for resource cleanup?ensure guarantees that cleanup code like closing files or releasing locks runs even if an error interrupts normal flow.Click to reveal answer
beginner
Example: What will this Ruby code print?
begin puts 'Start' raise 'Oops' rescue puts 'Rescued' ensure puts 'Always runs' end
It prints:<br>Start<br>Rescued<br>Always runs<br>The
ensure block runs last no matter what.Click to reveal answer
What does the
ensure block guarantee in Ruby?✗ Incorrect
The
ensure block always runs after begin, regardless of exceptions.Which block handles exceptions in Ruby?
✗ Incorrect
rescue handles exceptions; ensure runs cleanup code.If an exception is raised in
ensure, what happens?✗ Incorrect
Exceptions in
ensure override previous exceptions and propagate.Where should you put code to close a file to ensure it always runs?
✗ Incorrect
Closing files should be in
ensure to guarantee execution.What will this code print?
begin puts 'Hello' ensure puts 'Goodbye' end
✗ Incorrect
Both
puts run; ensure runs after begin.Explain how the
ensure block works in Ruby and why it is important for cleanup.Think about what happens when errors occur and you still want to clean up.
You got /4 concepts.
Describe the difference between
rescue and ensure blocks in Ruby exception handling.One catches errors, the other guarantees code runs.
You got /4 concepts.