try / catch / finally
try {
$response = $api->fetchUser($id);
} catch (NetworkException $e) {
logger()->warning('Netzwerkfehler: ' . $e->getMessage());
return null;
} catch (AuthException $e) {
logger()->error('Authentifizierung fehlgeschlagen', ['token' => '***']);
throw $e; // weiterreichen
} finally {
$api->disconnect(); // wird immer ausgeführt
}
Mehrere Exception-Typen in einem catch (PHP 8.0+)
try {
// ...
} catch (NotFoundException | ValidationException $e) {
return response()->json(['error' => $e->getMessage()], 400);
}
Eigene Exceptions
final class InsufficientFundsException extends \DomainException
{
public static function forAmount(int $requested, int $available): self
{
return new self("Fehlbetrag: $requested Cent angefragt, nur $available verfügbar.");
}
}
// Aufruf:
throw InsufficientFundsException::forAmount(5000, 2000);
Exceptions als Ausdruck werfen (PHP 8.0+)
throw ist seit PHP 8 ein Ausdruck — nutzbar in ternären Operatoren, match-Blöcken und Null-Coalescing:
$user = User::find($id) ?? throw new NotFoundException("User $id");
$role = match ($input) {
'admin', 'user' => $input,
default => throw new InvalidArgumentException("Ungültige Rolle: $input"),
};
Faustregel
- Werfe eine präzise Exception (nicht
\Exception). - Fange nur, wenn du sinnvoll darauf reagieren kannst.
- Nutze
DomainExceptionfür Business-Fehler,RuntimeExceptionfür Umgebungsfehler. - Logge inkl. Kontext, aber niemals Passwörter, Tokens, PII.