throw komandası
throw komandası PHP-də açıq şəkildə istisna yaratmaq üçün istifadə olunur.
O, bir parametr qəbul edir - istisna obyekti, hansı ki, əsas Exception sinfindən miras alan sinifin nümunəsi olmalıdır.
Bu funksiya çağırıldıqda, cari kodun icrası dərhal dayandırılır və PHP istisnanı emal etmək üçün uyğun catch blokunu axtarır.
Sintaksis
throw new ExceptionClass(message, code, previous);
Nümunə
İstisna yaratmağın sadə nümunəsi:
<?php
$age = -5;
if ($age < 0) {
throw new Exception('Age cannot be negative');
}
?>
Kodun icrasının nəticəsi:
Fatal error: Uncaught Exception: Age cannot be negative
Nümunə
İstisnanın emalı ilə nümunə:
<?php
try {
$res = 10 / 0;
if (is_infinite($res)) {
throw new Exception('Division by zero');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Kodun icrasının nəticəsi:
'Error: Division by zero'
Nümunə
Xüsusi istisnanın istifadəsi:
<?php
class MyCustomException extends Exception {}
try {
throw new MyCustomException('Custom error message');
} catch (MyCustomException $e) {
echo 'Custom error caught: ' . $e->getMessage();
}
?>
Kodun icrasının nəticəsi:
'Custom error caught: Custom error message'