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

phptry {
  // Istisno chiqarishi mumkin bo‘lgan kod
} catch (ExceptionType $e) {
  // Istisnoni qayta ishlash
}

Misol

Istisnoni qayta ishlashning oddiy misoli:

php<?php
  try {
    throw new Exception('Something went wrong');
  } catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage();
  }
?>

Kod bajarilishi natijasi:

php'Caught exception: Something went wrong'

Misol

Turli xil istisno turlarini qayta ishlash:

php<?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:

php'Invalid argument: Invalid argument'
yoki
'Runtime error: Runtime error'

Shuningdek qarang

  • try konstruksiyasi,
    bu istisnolarni qayta ishlash uchun kod blokini belgilaydi
  • throw konstruksiyasi,
    bu istisno chiqaradi
  • Exception klassi,
    bu barcha istisnolar uchun asosiy klass hisoblanadi