PHP menggunakan Exception untuk menangani error secara terstruktur.
Try/Catch:
try {
$result = riskyOperation();
echo $result;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
// Selalu dijalankan (optional)
cleanup();
}
Throwing exception:
function bagi(int $a, int $b): float {
if ($b === 0) {
throw new InvalidArgumentException("Tidak bisa dibagi nol!");
}
return $a / $b;
}
try {
echo bagi(10, 0);
} catch (InvalidArgumentException $e) {
echo $e->getMessage(); // "Tidak bisa dibagi nol!"
}
Custom exception:
class InsufficientBalanceException extends Exception {
public function __construct(float $balance, float $amount) {
parent::__construct(
"Saldo tidak cukup. Saldo: $balance, Dicoba: $amount"
);
}
}
function transfer(float $amount): void {
$balance = getBalance();
if ($balance < $amount) {
throw new InsufficientBalanceException($balance, $amount);
}
// ... proses transfer
}