Throw Exceptions from Expressions in PHP 8.0

Throw Exceptions from Expressions in PHP 8.0

In versions prior to PHP 8.0, the throw keyword is a statement. It means that throw cannot be used in places where only a single expression is expected.

Since PHP 8.0, the throw keyword is an expression and may be used in arrow functions, the null coalescing (??) and ternary (:?) operators, or in other places where a single expression is accepted.

  • throw usage with arrow function:
<?php

$fn = fn() => throw new Exception('Not implemented');
$fn();
  • throw usage with null coalescing operator:
<?php

$id = $_GET['id'] ?? throw new Exception('Variable is not set or value is null');
  • throw usage with ternary operator:
<?php

$id = isset($user) ? $user->id : throw new Exception('Variable is not set or value is null');
  • throw usage with shorthand ternary operator:
<?php

$_POST['id'] = 0;
$id = $_POST['id'] ?: throw new Exception('Variable is falsy');
  • throw usage with if statement:
<?php

if (isset($_GET['id']) || throw new Exception('Variable is not set or value is null')) {
    $id = (int) $_GET['id'];
}

Leave a Comment

Cancel reply

Your email address will not be published.