Challenge - Error handling
Build a robust order system with try/catch, throw and custom exceptions.
Challenge - Error handling
In this challenge you'll build a robust order system. You'll define a custom exception class named InvalidOrderException and throw it with throw inside the processOrder(int $quantity, float $price): float function.
An invalid quantity or a negative price throws the exception. The calling code catches it with a try/catch block and prints the error message. This tests your full intermediate error-handling knowledge.
try, catch, throw flow
You define a custom exception with class InvalidOrderException extends Exception {}; the class inherits all of Exception's methods. It is thrown with throw new InvalidOrderException("message").
The try block wraps risky code; catch (InvalidOrderException $e) catches only this type. $e->getMessage() reads the error message. This is the standard way to propagate errors safely to the caller.
Exercise Write InvalidOrderException and processOrder
First define the custom exception with class InvalidOrderException extends Exception {}. Then write processOrder(int $quantity, float $price): float: if $quantity <= 0 throw new InvalidOrderException("Invalid quantity"); if $price < 0 throw new InvalidOrderException("Negative price"). Otherwise return $quantity * $price. Add the call try { echo processOrder(0, 100) . "\n"; } catch (InvalidOrderException $e) { echo "Error: " . $e->getMessage() . "\n"; }.
Show example solution
" . $e->getMessage() . "\n"; }.
Example solution:
<?php
// Write InvalidOrderException class and processOrder function
class InvalidOrderException extends Exception {}
function processOrder(int $quantity, float $price): float {
if ($quantity <= 0) {
throw new InvalidOrderException("Invalid quantity");
}
if ($price < 0) {
throw new InvalidOrderException("Negative price");
}
return $quantity * $price;
}
try {
echo processOrder(0, 100) . "\n";
} catch (InvalidOrderException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Test yourself
-
Which class do you extend when creating a custom exception?
- stdClass
- Error
- Throwable
- Exception
Show answer
Exception — Correct. class InvalidOrderException extends Exception inherits all exception methods.
-
Complete the throw statement
if ($quantity === 0) { ____ new InvalidOrderException("Quantity required"); }Show answer
if ($quantity === 0) { throw new InvalidOrderException("Quantity required"); } -
Match each error-handling keyword
- try
- wraps risky code
- catch
- catches error
- throw
- raises error
- finally
- always runs