Catch-funktio
Funktio catch on osa try-catch-lohkoa ja palvelee poikkeusten sieppaamiseen, jotka voidaan heittää try-lohkossa. Poikkeuksen ilmaantuessa koodin suoritus siirtyy vastaavaan catch-lohkoon, jossa virhe voidaan käsitellä.
Syntaksi
try {
// Koodi, joka voi heittää poikkeuksen
} catch (ExceptionType $e) {
// Poikkeuksen käsittely
}
Esimerkki
Yksinkertainen esimerkki poikkeuksen käsittelystä:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Koodin suorituksen tulos:
'Caught exception: Something went wrong'
Esimerkki
Eri tyyppisten poikkeusten käsittely:
<?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();
}
?>
Mahdolliset koodin suorituksen tulokset:
'Invalid argument: Invalid argument'
tai
'Runtime error: Runtime error'