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?"
Practice
What is the main purpose of creating a custom exception class in PHP?
Solution
Step 1: Understand the role of custom exceptions
Custom exceptions allow programmers to create specific error types that represent particular problems in the code.Step 2: Compare with other options
Custom exceptions do not replace the built-in Exception class, nor do they speed up execution or fix errors automatically.Final Answer:
To define specific error types for clearer error handling -> Option AQuick Check:
Custom exceptions = Specific error types [OK]
- Thinking custom exceptions replace built-in Exception
- Believing custom exceptions fix errors automatically
- Assuming custom exceptions improve performance
Which of the following is the correct way to declare a custom exception class named MyError in PHP?
?Solution
Step 1: Recall PHP syntax for custom exceptions
Custom exceptions extend the built-in Exception class using the keywordextends.Step 2: Check each option
class MyError extends Exception {} correctly usesextends Exception. class MyError implements Exception {} wrongly usesimplements, which is for interfaces. class MyError extends Error {} extendsError, which is a different base class. class MyError inherits Exception {} uses invalid syntaxinherits.Final Answer:
class MyError extends Exception {} -> Option CQuick Check:
Custom exception syntax = extends Exception [OK]
- Using 'implements' instead of 'extends'
- Using 'inherits' keyword which is invalid
- Extending Error instead of Exception
What will be the output of the following PHP code?
class MyException extends Exception {}
try {
throw new MyException("Custom error happened");
} catch (MyException $e) {
echo $e->getMessage();
} catch (Exception $e) {
echo "General error";
}Solution
Step 1: Understand the thrown exception type
The code throws an exception of typeMyException.Step 2: Check catch blocks order and matching
The first catch block matchesMyException, so it catches the exception and echoes the message.Final Answer:
Custom error happened -> Option AQuick Check:
Matching catch block runs = Custom message [OK]
- Expecting general catch to run first
- Thinking exception is uncaught
- Ignoring exception message
Identify the error in this PHP code that defines and uses a custom exception:
class MyException extends Exception {}
try {
throw new MyException("Error!");
} catch (Exception $e) {
echo $e->getMessage();
} catch (MyException $e) {
echo "Caught MyException";
}Solution
Step 1: Analyze catch block order
The first catch block catches all Exception types, including MyException, so the second catch block is unreachable.Step 2: Correct catch order
Specific exceptions like MyException must be caught before the general Exception to avoid unreachable code.Final Answer:
The catch blocks are in wrong order; specific should come before general -> Option BQuick Check:
Specific catch before general catch [OK]
- Placing general catch before specific catch
- Thinking implements is needed for exceptions
- Misunderstanding throw syntax
Given this custom exception class and code, what will be the output?
class ValidationException extends Exception {
public function getCustomMessage() {
return "Validation failed: " . $this->getMessage();
}
}
try {
throw new ValidationException("Invalid input");
} catch (ValidationException $e) {
echo $e->getCustomMessage();
} catch (Exception $e) {
echo "General error";
}Solution
Step 1: Understand the custom method in exception
The classValidationExceptionadds a methodgetCustomMessage()that returns a formatted message.Step 2: Check which catch block runs and output
The thrown exception isValidationException, so the first catch block runs and echoes the custom message.Final Answer:
Validation failed: Invalid input -> Option DQuick Check:
Custom method called on caught exception [OK]
- Expecting default getMessage() output only
- Thinking general catch block runs first
- Assuming method does not exist
Ready to prove it?
Pass the test and this pattern moves unknown
