Exceptions in PHP
try, catch, finally and a custom exception class of your own.
<?php
class EmptyCartException extends RuntimeException {}
function checkout(array $items): int {
if ($items === []) {
throw new EmptyCartException("nothing to buy");
}
return array_sum($items);
}
try {
echo checkout([5, 8]), "\n";
echo checkout([]), "\n";
} catch (EmptyCartException $e) {
echo "refused: ", $e->getMessage(), "\n";
} finally {
echo "till closed\n";
}
How it works
- Extending
RuntimeExceptionnames a failure precisely. throwabortscheckoutbefore it can sum an empty cart.catchmatches by class and binds the error to$e.finallyruns on success and failure alike.
Keywords and builtins used here
EmptyCartExceptionarrayarray_sumcatchcheckoutclassechoextendsfinallyfunctionifnewreturnthrowtry
The run, in numbers
- Lines
- 18
- Characters to type
- 370
- Tokens
- 86
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 64 seconds.
Step 2 of 3 in Null & errors, step 20 of 27 in Language basics.