Begin/rescue/end blocks in Ruby - Time & Space Complexity
When we use begin/rescue/end blocks in Ruby, we want to know how the time to run the code changes as the input grows.
We ask: How much extra time does handling errors add when the input size changes?
Analyze the time complexity of the following code snippet.
begin
numbers = [1, 2, 3, 4, 5]
total = 0
numbers.each do |num|
total += 10 / num
end
rescue ZeroDivisionError
puts "Cannot divide by zero!"
end
This code sums 10 divided by each number in an array, and handles division by zero errors if they occur.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array with
each. - How many times: Once for every element in the array (n times).
As the array gets bigger, the number of divisions and additions grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 divisions and additions |
| 100 | About 100 divisions and additions |
| 1000 | About 1000 divisions and additions |
Pattern observation: The work grows evenly as the input grows; doubling input doubles work.
Time Complexity: O(n)
This means the time to run the code grows in direct proportion to the number of items in the array.
[X] Wrong: "The rescue block makes the whole code run slower for every item in the array."
[OK] Correct: The rescue block only runs if an error happens. If no error occurs, it does not slow down the loop itself.
Understanding how error handling affects time helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the rescue block handled errors inside the loop instead of outside? How would the time complexity change?"
Practice
begin/rescue/end block in Ruby?Solution
Step 1: Understand the role of
Thebeginblockbeginblock contains code that might cause an error.Step 2: Understand the role of
Therescueblockrescueblock catches errors and handles them so the program doesn't crash.Final Answer:
To handle errors and prevent the program from crashing -> Option DQuick Check:
begin/rescue = error handling [OK]
- Thinking begin/rescue creates loops
- Confusing rescue with method definition
- Using begin/rescue to declare variables
begin/rescue/end in Ruby?Solution
Step 1: Identify Ruby syntax for error handling
Ruby usesbegin,rescue, andendkeywords for exceptions.Step 2: Compare options with Ruby syntax
begin risky_code rescue handle_error end matches Ruby syntax exactly; others use syntax from other languages or incorrect keywords.Final Answer:
begin\n risky_code\nrescue\n handle_error\nend -> Option AQuick Check:
Ruby error handling = begin/rescue/end [OK]
- Using try/catch like other languages
- Using if/else for error handling
- Mixing Python or JavaScript syntax
begin puts 10 / 0 rescue ZeroDivisionError puts "Cannot divide by zero" end
Solution
Step 1: Identify the error in the code
The code tries to divide 10 by 0, which raises a ZeroDivisionError.Step 2: Understand the rescue block
The rescue block catches ZeroDivisionError and prints "Cannot divide by zero" instead of crashing.Final Answer:
Cannot divide by zero -> Option AQuick Check:
ZeroDivisionError caught = message printed [OK]
- Expecting program to crash
- Thinking it prints 0 or 10
- Confusing error name with output
begin puts 5 + "3" rescue puts "Error caught" end
Solution
Step 1: Analyze the operation inside begin block
Adding 5 (number) and "3" (string) causes a TypeError in Ruby.Step 2: Check error handling
The rescue block catches any error and prints "Error caught"; the error is due to incompatible types.Final Answer:
You cannot add a number and a string directly -> Option CQuick Check:
Type mismatch causes error caught [OK]
- Thinking rescue needs error type always
- Assuming code runs without error
- Confusing begin with try
begin # risky code rescue puts "An error occurred" end
Solution
Step 1: Understand handling multiple errors
Ruby allows multiple rescue clauses to catch different error types separately.Step 2: Apply multiple rescue clauses
Write rescue clauses likerescue ZeroDivisionErrorandrescue IOErrorto handle errors distinctly.Final Answer:
Use multiple rescue clauses with specific error classes -> Option BQuick Check:
Multiple rescue = specific error handling [OK]
- Using else instead of rescue
- Trying to catch errors with if statements
- Putting code inside rescue block
Ready to prove it?
Pass the test and this pattern moves unknown
