Catch funksiyasi
catch funksiyası try-catch blokunun bir hissəsidir və try blokunda atıla biləcək istisnaları tutmaq üçün xidmət edir. Bir istisna baş verəndə kod icrası müvafiq catch blokuna keçir, burada səhv emal edilə bilər.
Sintaksis
try {
// Istisna atıla biləcək kod
} catch (ExceptionType $e) {
// Istisnanın emalı
}
Nümunə
Sadə bir istisna emalı nümunəsi:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Kodun icra nəticəsi:
'Caught exception: Something went wrong'
Nümunə
Müxtəlif tipli istisnaların emalı:
<?php
try {
if (rand(0, 1)) {
throw new InvalidArgumentException('Invalid argument');
} else {
throw new RuntimeException('Runtime error');
}
} catch (InvalidArgumentException $e) {
echo 'Invalid argument: ' . $e->getMessage();
} catch (RuntimeException $e) {
echo 'Runtime error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'Generic exception: ' . $e->getMessage();
}
?>
Kodun icrasının mümkün nəticələri:
'Invalid argument: Invalid argument'
və ya
'Runtime error: Runtime error'