IntermediateLesson 11 of 16
Exceptions & Error Handling – PHP
try/catch/finally, custom exceptions, Error vs. Exception and strict_types.
In PHP 8, errors are thrown as objects almost everywhere. The base is the Throwable interface, below it are Exception (runtime errors you want to handle) and Error (programming errors like TypeError or DivisionByZeroError).
<?php
function abheben(float $saldo, float $betrag): float {
if ($betrag > $saldo) {
throw new InvalidArgumentException("Not enough balance");
}
return $saldo - $betrag;
}
try {
echo abheben(50, 100);
} catch (InvalidArgumentException $e) {
echo "Error: ", $e->getMessage(), "\n";
} finally {
echo "Done\n";
}Custom exceptions make the cause of an error unambiguous. With previous you chain the original error. A catch block can catch several types, and since PHP 8 throw is also an expression.
<?php
class KontoFehler extends RuntimeException {
public function __construct(string $msg, private float $fehlbetrag = 0.0, ?Throwable $prev = null) {
parent::__construct($msg, 0, $prev);
}
public function fehlbetrag(): float { return $this->fehlbetrag; }
}
try {
throw new KontoFehler("Not enough balance", 50.0);
} catch (KontoFehler | LogicException $e) {
echo $e->getMessage(), " (", $e->fehlbetrag(), ")\n";
}
$konfig = ["host" => "localhost"];
try {
$port = $konfig["port"] ?? throw new UnexpectedValueException("port missing");
} catch (UnexpectedValueException $e) {
echo $e->getMessage(), "\n";
}<?php
declare(strict_types=1);
try {
echo intdiv(1, 0);
} catch (DivisionByZeroError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n"; // DivisionByZeroError: Division by zero
}
try {
echo strlen([]);
} catch (TypeError $e) {
echo "TypeError caught\n";
}WarningIn production, never show error messages in the browser (
display_errors=0); write them to the log instead (log_errors=1, error_log()). Messages reveal paths, SQL and sometimes passwords.TipOnly catch what you can sensibly handle. A
catch (Throwable $e) { } with no reaction hides bugs – let unexpected errors bubble up to a central handler (set_exception_handler).