Why error handling uses rescue in Ruby - Performance Analysis
When we use rescue in Ruby, it helps handle errors that might happen during a program's run.
We want to understand how using rescue affects how long the program takes to run as the input grows.
Analyze the time complexity of the following code snippet.
def divide_numbers(numbers, divisor)
results = []
numbers.each do |num|
begin
results << num / divisor
rescue ZeroDivisionError
results << nil
end
end
results
end
This code divides each number in a list by a divisor, using rescue to handle division by zero errors.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list and dividing it.
- How many times: Once for each number in the input list.
As the list of numbers gets bigger, the program does more divisions and checks for errors.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 divisions and error checks |
| 100 | About 100 divisions and error checks |
| 1000 | About 1000 divisions and error checks |
Pattern observation: The work grows directly with the number of items; doubling the list doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items to process.
[X] Wrong: "Using rescue makes the program slower in a way that changes how time grows with input size."
[OK] Correct: The rescue only runs when an error happens, so it doesn't add extra loops or repeated work for every item.
Understanding how error handling fits into time complexity shows you can think about both program correctness and efficiency together.
"What if the code used nested loops inside the begin block? How would the time complexity change?"