In versions prior to PHP 8.0, in order to catch an exception, we need to store it in a variable. However, there can be situations when variable is not used. In the following example, we need to specify the variable in the catch
block even if it's not used:
<?php
class AccessDeniedToDeleteDataException extends Exception {};
function deleteData() {
throw new AccessDeniedToDeleteDataException('Denied');
}
try {
deleteData();
} catch (AccessDeniedToDeleteDataException $exception) {
echo 'Delete data not allowed';
}
In our case, the exception type AccessDeniedToDeleteDataException
is clear enough to convey an idea of the exception. So, the details about exception are irrelevant.
Since PHP 8.0, we can omit a variable in the catch
block.
<?php
// ...
try {
deleteData();
} catch (AccessDeniedToDeleteDataException) {
echo 'Delete data not allowed';
}
Note that exceptions such as Exception
or Throwable
are too general, and catching them without capturing them to variables might be a bad practice.
Leave a Comment
Cancel reply