
Wikis & learning
Handle a bad value with an exception
A function with a clear input contract can tell its caller when a value falls outside that contract.
A function with a clear input contract can tell its caller when a value falls outside that contract.
How it works
Throw an exception at the boundary and catch the specific type where the application can provide a useful message.
PHP example
<?php
function copies(int $count): int {
if ($count < 1) {
throw new InvalidArgumentException('Choose at least one copy');
}
return $count;
}
try {
echo copies(0);
} catch (InvalidArgumentException $error) {
echo $error->getMessage();
}Expected result
Choose at least one copy
Try a variation
Try a positive argument and check that the catch block no longer runs.
Discussion
Sign in to participate.



