Fungsi catch
Fungsi catch adalah sebahagian daripada blok try-catch dan berfungsi untuk menangkap pengecualian yang mungkin dibuang dalam blok try. Apabila pengecualian berlaku, pelaksanaan kod beralih ke blok catch yang sepadan, di mana ralat boleh diproses.
Sintaks
try {
// Kod yang mungkin membuang pengecualian
} catch (ExceptionType $e) {
// Pemprosesan pengecualian
}
Contoh
Contoh mudah pemprosesan pengecualian:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Hasil pelaksanaan kod:
'Caught exception: Something went wrong'
Contoh
Pemprosesan jenis pengecualian yang berbeza:
<?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();
}
?>
Keputusan mungkin pelaksanaan kod:
'Invalid argument: Invalid argument'
atau
'Runtime error: Runtime error'