Custom exception classes in Ruby - Time & Space Complexity
When we create custom exception classes in Ruby, we want to know how this affects the program's speed.
We ask: How does the time to run change as the program grows or uses these exceptions?
Analyze the time complexity of the following code snippet.
class MyError < StandardError
end
def check_value(x)
raise MyError, "Value too small" if x < 10
return x
end
values = [5, 15, 8, 20]
values.each do |v|
begin
puts check_value(v)
rescue MyError => e
puts e.message
end
end
This code defines a custom error and uses it to check values in a list, raising the error if a value is too small.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array with
eachand callingcheck_valuefor each item. - How many times: Once for each element in the array (n times).
As the number of values grows, the program checks each one in turn.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks and possible exceptions |
| 100 | 100 checks and possible exceptions |
| 1000 | 1000 checks and possible exceptions |
Pattern observation: The work grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of values checked.
[X] Wrong: "Creating a custom exception makes the program slower in a way that changes the overall time complexity."
[OK] Correct: Defining a custom exception class is a one-time setup and does not add repeated work per item; it does not change how the program scales with input size.
Understanding how exceptions affect program speed helps you write clear and efficient error handling, a skill valued in real projects and interviews.
"What if we raised the exception inside a nested loop over the array? How would the time complexity change?"