Handle errors with try / catch

Wrap risky code in try. Catch the specific exception you expect and always have a safe fallback.

PHP · Handle errors with try / catchBeginner
function divide(int $a, int $b): float
{
    if ($b === 0) {
        throw new InvalidArgumentException('Cannot divide by zero');
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (InvalidArgumentException $e) {
    echo 'Problem: ' . $e->getMessage();
} catch (Throwable $e) {
    error_log($e->getMessage());       // anything else: log it, show a generic message
    echo 'Something went wrong.';
} finally {
    // runs always (close files, release locks)
}
exceptiontrycatcherrors