Fungsi catch
Fungsi catch adalah bagian dari blok try-catch dan berfungsi untuk menangkap pengecualian yang mungkin dilempar dalam blok try. Ketika pengecualian terjadi, eksekusi kode beralih ke blok catch yang sesuai, di mana kesalahan dapat ditangani.
Sintaks
try {
// Kode yang mungkin melemparkan pengecualian
} catch (ExceptionType $e) {
// Penanganan pengecualian
}
Contoh
Contoh sederhana penanganan pengecualian:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Hasil eksekusi kode:
'Caught exception: Something went wrong'
Contoh
Penanganan berbagai jenis pengecualian:
<?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();
}
?>
Kemungkinan hasil eksekusi kode:
'Invalid argument: Invalid argument'
atau
'Runtime error: Runtime error'