Función catch
La función catch es parte del bloque try-catch y sirve para interceptar excepciones que pueden ser lanzadas en el bloque try. Cuando ocurre una excepción, la ejecución del código pasa al bloque catch correspondiente, donde se puede manejar el error.
Sintaxis
try {
// Código que puede lanzar una excepción
} catch (ExceptionType $e) {
// Manejo de la excepción
}
Ejemplo
Un ejemplo simple de manejo de excepciones:
<?php
try {
throw new Exception('Something went wrong');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>
Resultado de la ejecución del código:
'Caught exception: Something went wrong'
Ejemplo
Manejo de diferentes tipos de excepciones:
<?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();
}
?>
Posibles resultados de la ejecución del código:
'Invalid argument: Invalid argument'
o
'Runtime error: Runtime error'