Throw buýrugy
throw buýrugy PHP-de ýalňyşlygy aýdan-ýagdaýda çykarmak üçin ulanylýar.
Ol bir parametr kabul edýär - Exception esas klasynyň mirasdary bolan klasyň nusgasy bolmaly ýalňyşlyk obýekti.
Bu funksiýa çagyrylýança, häzirki kodyň ýerine ýetirilişi derrew togtalýar we PHP ýalňyşlygy işlemek üçin degişli catch blogyny tapmaga synanyşýar.
Sintaksis
throw new ExceptionClass(message, code, previous);
Mysal
Ýalňyşlyk döretmegiň ýönekeý mysaly:
<?php
$age = -5;
if ($age < 0) {
throw new Exception('Age cannot be negative');
}
?>
Kodyň ýerine ýetiriliş netijesi:
Fatal error: Uncaught Exception: Age cannot be negative
Mysal
Ýalňyşlygy işleýän mysal:
<?php
try {
$res = 10 / 0;
if (is_infinite($res)) {
throw new Exception('Division by zero');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Kodyň ýerine ýetiriliş netijesi:
'Error: Division by zero'
Mysal
Ulanyjy ýalňyşlygynyň ulanylmagy:
<?php
class MyCustomException extends Exception {}
try {
throw new MyCustomException('Custom error message');
} catch (MyCustomException $e) {
echo 'Custom error caught: ' . $e->getMessage();
}
?>
Kodyň ýerine ýetiriliş netijesi:
'Custom error caught: Custom error message'