Käsk throw
Käsku throw kasutatakse erandi selgesõnaliseks viskamiseks PHP-s.
See võtab ühe parameetri - erandi objekti, mis peab olema klassi eksemplar,
mis on päritud baasklassist Exception. Selle funktsiooni väljakutsumisel praegune
koodi täitmine kohe peatub ja PHP proovib leida vastava catch ploki erandi töötlemiseks.
Süntaks
throw new ExceptionClass(message, code, previous);
Näide
Lihtne näide erandi genereerimisest:
<?php
$age = -5;
if ($age < 0) {
throw new Exception('Age cannot be negative');
}
?>
Koodi täitmise tulemus:
Fatal error: Uncaught Exception: Age cannot be negative
Näide
Näide erandi töötlemisega:
<?php
try {
$res = 10 / 0;
if (is_infinite($res)) {
throw new Exception('Division by zero');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Koodi täitmise tulemus:
'Error: Division by zero'
Näide
Kohandatud erandi kasutamine:
<?php
class MyCustomException extends Exception {}
try {
throw new MyCustomException('Custom error message');
} catch (MyCustomException $e) {
echo 'Custom error caught: ' . $e->getMessage();
}
?>
Koodi täitmise tulemus:
'Custom error caught: Custom error message'