Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Exceptions

A program cannot always do what it is asked: a file is missing, the data is invalid, something divides by zero. Exceptions are a way to report such a situation and handle it in the right place.

throw and try/catch

The throw statement throws an exception: the function stops running. You catch it with a catch block, and the code where it may occur goes inside try:

<?php
 
function divide(int $a, int $b): float
{
    if ($b === 0) {
        throw new InvalidArgumentException('Cannot divide by zero');
    }
 
    return $a / $b;
}
 
try {
    echo divide(10, 2), "\n";
    echo divide(1, 0);
} catch (InvalidArgumentException $e) {
    echo 'Error: ', $e->getMessage();
}

The first call succeeded, the second threw an exception, and control jumped straight to catch. The getMessage() method returns the text passed when the exception was created.

What happens without catch

If nobody catches an exception, the program stops with a Fatal error: Uncaught ... message. So an exception must be handled at least at the top level of the program.

finally

The finally block always runs — after a successful try and after catch alike. It is the place to release resources: close files and connections.

<?php
 
try {
    echo "Opening the file\n";
    throw new RuntimeException('Read failure');
} catch (RuntimeException $e) {
    echo $e->getMessage(), "\n";
} finally {
    echo 'Closing the file';
}

Custom exceptions

An exception is an object of a class, so you can create your own by extending Exception. A separate class lets you catch exactly that error without confusing it with others:

<?php
 
class NotEnoughMoney extends Exception {}
 
function pay(int $balance, int $price): int
{
    if ($price > $balance) {
        throw new NotEnoughMoney('Short by ' . ($price - $balance));
    }
 
    return $balance - $price;
}
 
try {
    pay(100, 250);
} catch (NotEnoughMoney $e) {
    echo $e->getMessage(); // Short by 150
}

Built-in errors

PHP itself throws exceptions for some errors — for example, integer division by zero or passing a value of the wrong type:

<?php
 
try {
    echo intdiv(1, 0);
} catch (DivisionByZeroError $e) {
    echo $e->getMessage(); // Division by zero
}

Language errors extend Error, while ordinary exceptions extend Exception. Their common type is Throwable.

A common mistake

An empty catch block swallows the error: the program carries on with wrong data, and the cause becomes very hard to find later. Catch only the exceptions you know how to handle, and never leave catch empty.

Thanks for reading!

Donate to the site — we work hard for you.