typestar

Exceptions in PHP

try, catch, finally and a custom exception class of your own.

<?php
class EmptyCartException extends RuntimeException {}

function checkout(array $items): int {
    if ($items === []) {
        throw new EmptyCartException("nothing to buy");
    }
    return array_sum($items);
}

try {
    echo checkout([5, 8]), "\n";
    echo checkout([]), "\n";
} catch (EmptyCartException $e) {
    echo "refused: ", $e->getMessage(), "\n";
} finally {
    echo "till closed\n";
}

How it works

  1. Extending RuntimeException names a failure precisely.
  2. throw aborts checkout before it can sum an empty cart.
  3. catch matches by class and binds the error to $e.
  4. finally runs on success and failure alike.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
370
Tokens
86
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 2 of 3 in Null & errors, step 20 of 27 in Language basics.

← Previous Next →

Exceptions in other languages