Custom exception classes in PHP - Time & Space 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?
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 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.
As n grows, the loop runs more times until it hits the exception at i = 5.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 6 (loop runs until i=5, then throws) |
| 100 | 6 (still stops at i=5) |
| 1000 | 6 (still stops at i=5) |
Pattern observation: The loop stops early due to the exception, so operations do not grow with input size.
Time Complexity: O(1)
This means the program runs in constant time because it stops at a fixed point regardless of input size.
[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.
Understanding how exceptions affect program flow helps you explain error handling clearly and shows you think about performance in real situations.
"What if the exception was thrown only after the loop finishes? How would the time complexity change?"