catch Fonksiyonu

catch fonksiyonu, try-catch bloğunun bir parçasıdır ve try bloğunda fırlatılabilecek istisnaları yakalamak için kullanılır. Bir istisna oluştuğunda, kod yürütmesi ilgili catch bloğuna geçer, böylece hatayı işleyebilirsiniz.

Sözdizimi

phptry {
  // İstisna fırlatabilecek kod
} catch (ExceptionType $e) {
  // İstisnayı işleme
}

Örnek

Basit bir istisna işleme örneği:

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

Kodun çalıştırma sonucu:

php'Caught exception: Something went wrong'

Örnek

Farklı istisna türlerini işleme:

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();
  }
?>

Kodun olası çalıştırma sonuçları:

php'Invalid argument: Invalid argument'
veya
'Runtime error: Runtime error'

Ayrıca Bakınız

  • try yapısı,
    istisnaları işlemek için bir kod bloğu tanımlar
  • throw yapısı,
    bir istisna fırlatır
  • Exception sınıfı,
    tüm istisnalar için temel sınıftır