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?
Practice
Which class is the root of the exception hierarchy in Ruby?
Solution
Step 1: Understand Ruby's exception hierarchy
In Ruby, all exceptions inherit from theExceptionclass, which is the root of the hierarchy.Step 2: Identify the root class
Other exception classes likeStandardErrorandRuntimeErrorare subclasses ofException.Final Answer:
Exception -> Option CQuick Check:
Root exception class = Exception [OK]
- Confusing StandardError as root
- Thinking RuntimeError is root
- Choosing specific error classes instead of root
Which of the following is the correct way to rescue only StandardError exceptions in Ruby?
begin # some code rescue ??? puts 'Error caught' end
Solution
Step 1: Understand rescue syntax
Therescuekeyword can specify which exception class to catch by naming it afterrescue.Step 2: Choose the correct exception class
To catch onlyStandardErrorexceptions, writerescue StandardError.Final Answer:
StandardError -> Option AQuick Check:
Rescue specific error = StandardError [OK]
- Using Exception catches too many errors
- Using RuntimeError misses other StandardErrors
- Using IOError catches unrelated errors
What will be the output of this Ruby code?
begin raise IOError, 'File error' rescue StandardError => e puts e.class end
Solution
Step 1: Identify the raised exception
The code raises anIOErrorwith message 'File error'.Step 2: Check rescue clause
The rescue catchesStandardErrorand its subclasses.IOErroris a subclass ofStandardError, so it is caught.Step 3: Output the exception class
The code printse.class, which isIOError.Final Answer:
IOError -> Option DQuick Check:
Raised error class = IOError [OK]
- Assuming rescue prints StandardError
- Confusing Exception with StandardError
- Thinking RuntimeError is printed
Find the error in this Ruby code snippet:
begin raise 'Oops!' rescue IOError puts 'IO error caught' end
Solution
Step 1: Analyze the raised error
Raising with a string'Oops!'creates aRuntimeErrorby default.Step 2: Check rescue clause type
The rescue only catchesIOError, but the raised error isRuntimeError, so it is not caught.Final Answer:
The rescue clause will not catch the raised error -> Option BQuick Check:
Rescue type mismatch causes uncaught error [OK]
- Thinking rescue catches all errors by default
- Believing string raise is invalid syntax
- Assuming rescue syntax is wrong
You want to catch all exceptions except system-exiting ones like SystemExit and Interrupt. Which class should you rescue to catch most errors but allow system exits?
Solution
Step 1: Understand exception classes for system exit
Classes likeSystemExitandInterruptinherit directly fromException, notStandardError.Step 2: Choose rescue class to exclude system exits
RescuingStandardErrorcatches most runtime errors but excludes system-exiting exceptions.Step 3: Confirm other options
RescuingExceptioncatches everything including system exits, which is usually not desired.Final Answer:
StandardError -> Option AQuick Check:
Rescue StandardError to exclude system exits [OK]
- Rescuing Exception catches system exits too
- Choosing RuntimeError misses some errors
- Confusing NoMethodError as base class
Ready to prove it?
Pass the test and this pattern moves unknown
