try Komutu

try yapısı, kod yürütülürken ortaya çıkabilecek istisnaları işlemeye izin verir. Potansiyel olarak riskli kod try bloğuna, istisna işleyici ise catch bloğuna yerleştirilir. Ayrıca, her durumda yürütülen bir finally bloğu da kullanılabilir.

Sözdizimi

phptry {
  // İstisna oluşturabilecek kod
} catch (ExceptionType $e) {
  // İstisnanın işlenmesi
} finally {
  // Her durumda yürütülecek kod
}

Ö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 yürütülme sonucu:

php'Caught exception: Something went wrong'

Örnek

finally bloğu kullanılan bir örnek:

php<?php
try {
  echo 'Try block executed';
} finally {
  echo ' - Finally block executed';
}
?>

Kodun yürütülme sonucu:

php'Try block executed - Finally block executed'

Örnek

Farklı istisna türlerinin işlenmesi:

php<?php
try {
  // Farklı istisnalar oluşturabilecek kod
  throw new InvalidArgumentException('Invalid argument');
} catch (InvalidArgumentException $e) {
  echo 'Invalid argument: ', $e->getMessage();
} catch (Exception $e) {
  echo 'Generic exception: ', $e->getMessage();
}
?>

Kodun yürütülme sonucu:

php'Invalid argument: Invalid argument'

Ayrıca Bakınız