Funkcija catch
Funkcija catch yra try-catch bloko dalis ir naudojama išimtims pagauti, kurios gali būti išmestos try bloke. Išmetus išimtį, kodas pereina į atitinkamą catch bloką, kur galima apdoroti klaidą.
Sintaksė
try {
// Kodas, kuris gali išmesti išimtį
} catch (ExceptionType $e) {
// Išimties apdorojimas
}
Pavyzdys
Paprasčiausias išimties apdorojimo pavyzdys:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Kodo vykdymo rezultatas:
'Caught exception: Something went wrong'
Pavyzdys
Skirtingų tipų išimčių apdorojimas:
<?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();
}
?>
Galimi kodo vykdymo rezultatai:
'Invalid argument: Invalid argument'
arba
'Runtime error: Runtime error'