Funktsioon catch
Funktsioon catch on osa try-catch plokist ja kasutatakse erindite püüdmiseks, mida võib visata plokis try. Erindi tekkimisel läheb koodi täitmine vastavasse plokki catch, kus saab vea töödelda.
Süntaks
try {
// Kood, mis võib visata erindi
} catch (ExceptionType $e) {
// Erindi töötlemine
}
Näide
Lihtsaim näide erindi töötlemisest:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Koodi täitmise tulemus:
'Caught exception: Something went wrong'
Näide
Erinevat tüüpi erindite töötlemine:
<?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();
}
?>
Võimalikud koodi täitmise tulemused:
'Invalid argument: Invalid argument'
või
'Runtime error: Runtime error'