Try-Catch and Custom Exceptions
PHP supports try-catch exception handling similar to other languages. PHP 8 added union types for catch blocks.
Example
<?php
// Basic try-catch
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo 'Error: ' . $e->getMessage();
} finally {
echo 'This always runs';
}
// Multiple catch types (PHP 8)
try {
// risky code
} catch (InvalidArgumentException | RangeException $e) {
echo 'Validation error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
// Custom exception
class InsufficientFundsException extends RuntimeException {
public function __construct(float $needed) {
parent::__construct("Need $$needed more");
}
}
function withdraw(float $amount, float $balance): float {
if ($amount > $balance) {
throw new InsufficientFundsException($amount - $balance);
}
return $balance - $amount;
}
?> 