0
0
Rubyprogramming~5 mins

Exception hierarchy in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Exception hierarchy
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the exception hierarchy grows taller, Ruby may need to check more ancestor classes to find a match.

Hierarchy Depth (n)Approx. Checks
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows linearly with the depth of the exception hierarchy.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the matching exception grows in a straight line as the hierarchy gets deeper.

Common Mistake

[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.

Interview Connect

Understanding how exception matching scales helps you write clear error handling and reason about program performance.

Self-Check

What if the exception hierarchy was very wide but shallow? How would that affect the time complexity?