Excepciones de PHP
¿Qué es una excepción?
Una excepción es un objeto que describe un error o un comportamiento inesperado de un script PHP.
Muchas funciones y clases de PHP lanzan excepciones.
Las funciones y clases definidas por el usuario también pueden generar excepciones.
Las excepciones son una buena manera de detener una función cuando se encuentra con datos que no puede usar.
Lanzar una excepción
La throw
instrucción permite que una función o método definido por el usuario genere una excepción. Cuando se lanza una excepción, el código que le sigue no se ejecutará.
Si no se detecta una excepción, se producirá un error fatal con un mensaje de "Excepción no detectada".
Intentemos lanzar una excepción sin atraparla:
Ejemplo
<?php
function divide($dividend, $divisor) {
if($divisor == 0)
{
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
echo divide(5, 0);
?>
El resultado será algo como esto:
Fatal error: Uncaught Exception: Division by zero in
C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4
La sentencia try... catch
Para evitar el error del ejemplo anterior, podemos usar la
try...catch
declaración para detectar excepciones y continuar el proceso.
Sintaxis
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
}
Ejemplo
Mostrar un mensaje cuando se lanza una excepción:
<?php
function divide($dividend, $divisor) {
if($divisor ==
0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo
divide(5, 0);
} catch(Exception $e) {
echo "Unable to divide.";
}
?>
El bloque catch indica qué tipo de excepción debe capturarse y el nombre de la variable que se puede usar para acceder a la excepción. En el ejemplo anterior, el tipo de excepción es Exception
y el nombre de la variable es $e
.
La declaración intentar... atrapar... finalmente
La try...catch...finally
instrucción se puede utilizar para detectar excepciones. El código en el
finally
bloque siempre se ejecutará independientemente de si se detectó una excepción. Si
finally
está presente, el catch
bloque es opcional.
Sintaxis
try {
code that can throw exceptions
} catch(Exception $e) {
code that runs when an exception is caught
} finally {
code that
always runs regardless of whether an exception was caught
}
Ejemplo
Muestra un mensaje cuando se lanza una excepción y luego indica que el proceso ha finalizado:
<?php
function divide($dividend, $divisor) {
if($divisor
== 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo
divide(5, 0);
} catch(Exception $e) {
echo "Unable to
divide. ";
} finally {
echo "Process complete.";
}
?>
Ejemplo
Muestra una cadena incluso si no se detectó una excepción:
<?php
function divide($dividend, $divisor) {
if($divisor == 0)
{
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} finally {
echo
"Process complete.";
}
?>
El objeto de excepción
El objeto de excepción contiene información sobre el error o el comportamiento inesperado que encontró la función.
Sintaxis
new Exception(message, code, previous)
Valores paramétricos
Parameter | Description |
---|---|
message | Optional. A string describing why the exception was thrown |
code | Optional. An integer that can be used used to easily distinguish this exception from others of the same type |
previous | Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter |
Métodos
Al capturar una excepción, la siguiente tabla muestra algunos de los métodos que se pueden usar para obtener información sobre la excepción:
Method | Description |
---|---|
getMessage() | Returns a string describing why the exception was thrown |
getPrevious() | If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null |
getCode() | Returns the exception code |
getFile() | Returns the full path of the file in which the exception was thrown |
getLine() | Returns the line number of the line of code which threw the exception |
Ejemplo
Información de salida sobre una excepción que se lanzó:
<?php
function divide($dividend, $divisor) {
if($divisor == 0)
{
throw new Exception("Division by zero", 1);
}
return $dividend / $divisor;
}
try {
echo
divide(5, 0);
} catch(Exception $ex) {
$code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
echo "Exception thrown in $file on line
$line: [Code $code]
$message";
}
?>
Referencia de excepción completa
Para obtener una referencia completa, vaya a nuestra Referencia completa de excepciones de PHP .
La referencia contiene descripciones y ejemplos de todos los métodos de excepción.