0
0
Rubyprogramming~5 mins

Custom exception classes in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom exception classes
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array with each and calling check_value for each item.
  • How many times: Once for each element in the array (n times).
How Execution Grows With Input

As the number of values grows, the program checks each one in turn.

Input Size (n)Approx. Operations
1010 checks and possible exceptions
100100 checks and possible exceptions
10001000 checks and possible exceptions

Pattern observation: The work grows directly with the number of items; doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of values checked.

Common Mistake

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

Interview Connect

Understanding how exceptions affect program speed helps you write clear and efficient error handling, a skill valued in real projects and interviews.

Self-Check

"What if we raised the exception inside a nested loop over the array? How would the time complexity change?"