Skip to main content

PHP8 Errors

·193 words·1 min·
Table of Contents

In this post let’s cover what’s new when it comes to error handling in PHP81

Throw expression2
#

Now throw can be used as an expression. The following is valid:

// This was previously not possible since arrow functions only accept a single expression while throw was a statement.
$callable = fn() => throw new Exception();

// $value is non-nullable.
$value = $nullableValue ?? throw new InvalidArgumentException();

// $value is truthy.
$value = $falsableValue ?: throw new InvalidArgumentException();

// $value is only set if the array is not empty.
$value = !empty($array)
    ? reset($array)
    : throw new InvalidArgumentException();

$condition && throw new Exception();
$condition || throw new Exception();
$condition and throw new Exception();
$condition or throw new Exception();

Non-capturing catches3
#

Pre PHP8 situation
#

PHP requires exceptions being caught to be captured to a variable:

try {
    changeImportantData();
} catch (PermissionException $ex) {
    echo "You don't have permission to do this";
}

PHP8
#

Now catching exceptions are allowed without capturing them into variables:

try {
    changeImportantData();
} catch (PermissionException) { // The intention is clear: exception details are irrelevant
    echo "You don't have permission to do this";
}