0
0
PHPprogramming~5 mins

Custom exception classes in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom exception classes
O(1)
Understanding Time Complexity

When we create custom exception classes in PHP, we want to know how this affects the time it takes for our program to run.

We ask: does adding custom exceptions change how long the program takes as it handles errors?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class MyException extends Exception {}

function testError($n) {
    for ($i = 0; $i < $n; $i++) {
        if ($i === 5) {
            throw new MyException("Error at 5");
        }
    }
}

try {
    testError(10);
} catch (MyException $e) {
    echo $e->getMessage();
}
    

This code defines a custom exception and throws it inside a loop when a condition is met.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A for-loop running from 0 to n-1.
  • How many times: Up to n times, but stops early when exception is thrown.
How Execution Grows With Input

As n grows, the loop runs more times until it hits the exception at i = 5.

Input Size (n)Approx. Operations
106 (loop runs until i=5, then throws)
1006 (still stops at i=5)
10006 (still stops at i=5)

Pattern observation: The loop stops early due to the exception, so operations do not grow with input size.

Final Time Complexity

Time Complexity: O(1)

This means the program runs in constant time because it stops at a fixed point regardless of input size.

Common Mistake

[X] Wrong: "Throwing a custom exception always makes the program slower as input grows."

[OK] Correct: In this example, the exception stops the loop early, so the program does not run longer with bigger input.

Interview Connect

Understanding how exceptions affect program flow helps you explain error handling clearly and shows you think about performance in real situations.

Self-Check

"What if the exception was thrown only after the loop finishes? How would the time complexity change?"