Exception hierarchy in Ruby - Time & Space Complexity
When working with exceptions in Ruby, it's important to understand how the program handles errors as it grows.
We want to see how the time to find the right exception class changes as the hierarchy grows.
Analyze the time complexity of searching for the correct exception class in this hierarchy.
class CustomError < StandardError; end
class NetworkError < CustomError; end
class TimeoutError < NetworkError; end
begin
raise TimeoutError, "Timeout happened"
rescue NetworkError => e
puts e.message
end
This code raises a TimeoutError and rescues it by matching against NetworkError, which is a parent class.
When an exception is raised, Ruby checks the exception classes in the hierarchy to find a matching rescue.
- Primary operation: Traversing up the exception class hierarchy.
- How many times: At most, once per ancestor class until a match is found.
As the exception hierarchy grows taller, Ruby may need to check more ancestor classes to find a match.
| Hierarchy Depth (n) | Approx. Checks |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows linearly with the depth of the exception hierarchy.
Time Complexity: O(n)
This means the time to find the matching exception grows in a straight line as the hierarchy gets deeper.
[X] Wrong: "Exception matching happens instantly no matter how deep the hierarchy is."
[OK] Correct: Ruby must check each ancestor class one by one until it finds a match, so deeper hierarchies take more time.
Understanding how exception matching scales helps you write clear error handling and reason about program performance.
What if the exception hierarchy was very wide but shallow? How would that affect the time complexity?