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
try {
// İ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
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage();
}
?>
Kodun yürütülme sonucu:
'Caught exception: Something went wrong'
Örnek
finally bloğu kullanılan bir örnek:
<?php
try {
echo 'Try block executed';
} finally {
echo ' - Finally block executed';
}
?>
Kodun yürütülme sonucu:
'Try block executed - Finally block executed'
Örnek
Farklı istisna türlerinin işlenmesi:
<?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:
'Invalid argument: Invalid argument'
Ayrıca Bakınız
-
istisna oluşturan
throwyapısı,
-
istisna işleyiciyi tanımlayan
set_exception_handlerişlevi,