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?"