Handling exceptions
It does not matter how easy and intuitive your application is designed to be, there will be bad usage from the user or just random errors of connectivity, and your code has to be ready to handle these scenarios so that the user experience is a good as possible. We call these scenarios exceptions: an element of the language that identifies a case that is not as we expected.
The try…catch block
Your code can throw exceptions manually whenever you think it necessary. For example, take the setId
method from the Unique
trait. Thanks to type hinting, we are enforcing the ID to be a numeric one, but that is as far as it goes. What would happen if someone tries to set an ID that is a negative number? The code right now allows it to go through, but depending on your preferences, you would like to avoid it. That would be a good place for an exception to happen. Let's see how we would add this check and consequent exception:
public function setId($id) {
if ($id < 0) {
...