Catch funktsiyasi
catch funktsiyasi try-catch blokining bir qismi bo‘lib, try blokida chiqarilishi mumkin bo‘lgan istisnolarni ushlash uchun xizmat qiladi. Istisno yuzaga kelganda, kod bajarilishi mos keladigan catch blokiga o‘tadi, bu erda xatolikni qayta ishlash mumkin.
Sintaksis
try {
// Istisno chiqarishi mumkin bo‘lgan kod
} catch (ExceptionType $e) {
// Istisnoni qayta ishlash
}
Misol
Istisnoni qayta ishlashning oddiy misoli:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Kod bajarilishi natijasi:
'Caught exception: Something went wrong'
Misol
Turli xil istisno turlarini qayta ishlash:
<?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();
}
?>
Kod bajarilishining mumkin bo‘lgan natijalari:
'Invalid argument: Invalid argument'
yoki
'Runtime error: Runtime error'