Try-catch execution flow in PHP - Time & Space Complexity
We want to understand how the time to run a try-catch block changes as the code inside it grows.
How does the program's work increase when exceptions might happen?
Analyze the time complexity of the following code snippet.
try {
for ($i = 0; $i < $n; $i++) {
if ($i === $errorAt) {
throw new Exception("Error at $i");
}
// some simple operation
}
} catch (Exception $e) {
// handle exception
}
This code loops up to n times and may throw an exception at a certain point.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop running up to n times.
- How many times: Up to n times, but may stop early if exception occurs.
The loop runs more times as n grows, but if an exception happens early, it stops sooner.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 loop steps |
| 100 | Up to 100 loop steps |
| 1000 | Up to 1000 loop steps |
Pattern observation: The work grows roughly in a straight line with n, unless an exception stops it early.
Time Complexity: O(n)
This means the time to run grows directly with the number of loop steps, unless interrupted by an exception.
[X] Wrong: "Try-catch blocks always slow down the code a lot regardless of what happens inside."
[OK] Correct: The try-catch itself adds little overhead; the main time depends on how many loop steps run before an exception or normal end.
Understanding how exceptions affect code flow and time helps you explain real-world program behavior clearly and confidently.
"What if the exception is thrown every time inside the loop? How would the time complexity change?"
Practice
What is the main purpose of a try-catch block in PHP?
Solution
Step 1: Understand the role of try-catch
The try block contains code that might cause an error, and the catch block handles that error.Step 2: Identify the purpose
This structure prevents the program from stopping abruptly by managing errors gracefully.Final Answer:
To handle errors without stopping the program -> Option AQuick Check:
Try-catch = error handling [OK]
- Thinking try-catch speeds up code
- Confusing try-catch with output commands
- Believing try-catch creates variables
Which of the following is the correct syntax to start a try-catch block in PHP?
?Solution
Step 1: Recall PHP try-catch syntax
PHP uses curly braces {} to define blocks after try and catch keywords.Step 2: Match correct syntax
try { /* code */ } catch (Exception $e) { /* handle */ } correctly uses try { } and catch (Exception $e) { } syntax.Final Answer:
try { /* code */ } catch (Exception $e) { /* handle */ } -> Option CQuick Check:
Curly braces with try and catch = correct syntax [OK]
- Using colons instead of braces
- Adding parentheses after try or catch
- Using square brackets instead of braces
What will be the output of this PHP code?
try {
echo "Start\n";
throw new Exception("Error happened");
echo "End\n";
} catch (Exception $e) {
echo "Caught: " . $e->getMessage() . "\n";
}
echo "Done\n";Solution
Step 1: Trace code inside try block
"Start" is printed, then an Exception is thrown, so the next echo "End" is skipped.Step 2: Catch block runs and prints message
The catch block prints "Caught: Error happened" and then after try-catch, "Done" is printed.Final Answer:
Start Caught: Error happened Done -> Option AQuick Check:
Exception stops try, catch prints message, then Done [OK]
- Thinking code after throw runs
- Missing catch block output
- Assuming program stops after exception
Find the error in this PHP code snippet:
try {
echo "Hello";
} catch {
echo "Error caught";
}Solution
Step 1: Check catch block syntax
In PHP, catch must specify the exception type and variable, like catch (Exception $e).Step 2: Identify missing part
The catch block here has no parentheses or variable, causing a syntax error.Final Answer:
Missing exception variable in catch parentheses -> Option BQuick Check:
Catch needs (Exception $e) [OK]
- Omitting exception variable in catch
- Thinking echo needs semicolon after last statement only
- Believing catch can come before try
Consider this PHP code:
function divide($a, $b) {
try {
if ($b == 0) {
throw new Exception("Division by zero");
}
return $a / $b;
} catch (Exception $e) {
return $e->getMessage();
}
}
echo divide(10, 2) . "\n";
echo divide(5, 0) . "\n";What will be the output?
Solution
Step 1: Analyze divide(10, 2)
Since 2 is not zero, division happens: 10 / 2 = 5 is returned.Step 2: Analyze divide(5, 0)
Since 0 triggers exception, catch returns the message "Division by zero".Final Answer:
5 Division by zero -> Option DQuick Check:
Valid division returns number; zero divisor returns error message [OK]
- Expecting zero instead of error message
- Thinking exception stops program without catch
- Confusing return values inside try-catch
Ready to prove it?
Pass the test and this pattern moves unknown
