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
try {
// İstisna fırlatabilecek kod
} catch (ExceptionType $e) {
// İstisnayı işleme
}
Ö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 çalıştırma sonucu:
'Caught exception: Something went wrong'
Örnek
Farklı istisna türlerini işleme:
<?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ı:
'Invalid argument: Invalid argument'
veya
'Runtime error: Runtime error'