Las excepciones

Tabla de contenidos

PHP tiene una gestión de excepciones similar a la que ofrecen otros lenguajes de programación. Una excepción puede ser lanzada ("throw") y atrapada ("catch") en PHP. El código debe estar rodeado de un bloque try para facilitar la captura de una excepción potencial. Cada try debe tener al menos un bloque catch o finally correspondiente.

Si una excepción es lanzada y el ámbito actual de la función no tiene un bloque catch, la excepción "subirá" la pila de llamadas de la función llamante hasta encontrar un bloque catch correspondiente. Todos los bloques finally encontrados serán ejecutados. Si la pila de llamadas se despliega hasta el ámbito global sin encontrar un bloque catch correspondiente, el programa será terminado con un error fatal a menos que se haya definido un gestor global de excepciones.

El objeto lanzado debe ser una instanceof Throwable. Intentar lanzar un objeto que no lo sea resultará en un error fatal emitido por PHP.

A partir de PHP 8.0.0, la palabra clave throw es una expresión y puede ser utilizada en cualquier contexto de expresiones. En las versiones anteriores era una declaración que debía estar en su propia línea.

catch

Un bloque catch define cómo reaccionar a una excepción que ha sido lanzada. Un bloque catch define uno o más tipos de excepciones o errores que puede gestionar, y opcionalmente una variable en la que asignar la excepción. (Esta variable era requerida en las versiones anteriores a PHP 8.0.0) El primer bloque catch que una excepción o error lanzado encuentre y que corresponda al tipo del objeto lanzado gestionará el objeto.

Varios bloques catch pueden ser utilizados para atrapar diferentes clases de excepciones. La ejecución normal (cuando ninguna excepción es lanzada en el bloque try) continúa después del último bloque catch definido en la secuencia. Las excepciones pueden ser lanzadas (throw) o relanzadas en un bloque catch. De lo contrario, la ejecución continuará después del bloque catch que ha sido desencadenado.

Cuando una excepción es lanzada, el código siguiente al procesamiento no será ejecutado y PHP intentará encontrar el primer bloque catch correspondiente. Si una excepción no es atrapada, un error fatal emitido por PHP será enviado con un mensaje "Uncaught Exception ..." indicando que la excepción no pudo ser atrapada a menos que un gestor de excepciones sea definido con la función set_exception_handler().

A partir de PHP 7.1, un bloque catch puede especificar múltiples excepciones utilizando el carácter pipe (|). Esto es útil cuando diferentes excepciones de jerarquías de clases diferentes son tratadas de la misma manera.

A partir de PHP 8.0.0, el nombre de variable para la excepción atrapada es opcional. Si no se especifica, el bloque catch será siempre ejecutado pero no tendrá acceso al objeto lanzado.

finally

Un bloque finally también puede ser especificado después de los bloques catch. El código dentro del bloque finally será siempre ejecutado después de los bloques try y catch, independientemente de si una excepción ha sido lanzada, antes de continuar con la ejecución normal.

Una interacción notable es entre un bloque finally y una declaración return. Si una declaración return es encontrada dentro de los bloques try o catch, el bloque finally será ejecutado de todos modos. Además, la declaración return es evaluada cuando es encontrada, pero el resultado será devuelto después de que el bloque finally sea ejecutado. Adicionalmente, si el bloque finally contiene también una declaración return, el valor del bloque finally es devuelto.

Gestor global de excepciones

Si una excepción es permitida subir hasta el ámbito global, puede ser atrapada por un gestor de excepciones global si ha sido definido. La función set_exception_handler() puede definir una función que será llamada en lugar de un bloque catch si ningún otro bloque es invocado. El efecto es esencialmente idéntico a rodear todo el programa en un bloque try-catch con esta función como catch.

Notas

Nota:

Las funciones internas de PHP utilizan principalmente el Error reporting, solo las extensiones orientadas a objetos utilizan las excepciones. De todos modos, los errores pueden ser fácilmente traducidos en excepciones con ErrorException. Sin embargo, esta técnica solo funciona para los errores no fatales.

Ejemplo #1 Convertir el error reporting en excepciones

<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
throw new
ErrorException($message, 0, $severity, $filename, $lineno);
}

set_error_handler('exceptions_error_handler');
?>

Sugerencia

La biblioteca estándar PHP (SPL) proporciona un buen número de excepciones adicionales.

Ejemplos

Ejemplo #2 Lanzar una excepción

<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('División por cero.');
}
return
1/$x;
}

try {
echo
inverse(5) . "\n";
echo
inverse(0) . "\n";
} catch (
Exception $e) {
echo
'Excepción recibida : ', $e->getMessage(), "\n";
}

// Continuar la ejecución
echo "¡Hola mundo!\n";
?>

El resultado del ejemplo sería:

0.2
Excepción recibida : División por cero.
¡Hola mundo!

Ejemplo #3 Gestión de la excepción con un bloque finally

<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('División por cero.');
}
return
1/$x;
}

try {
echo
inverse(5) . "\n";
} catch (
Exception $e) {
echo
'Excepción recibida : ', $e->getMessage(), "\n";
} finally {
echo
"Primer final.\n";
}

try {
echo
inverse(0) . "\n";
} catch (
Exception $e) {
echo
'Excepción recibida : ', $e->getMessage(), "\n";
} finally {
echo
"Segundo final.\n";
}

// Continuar la ejecución
echo "¡Hola mundo!\n";
?>

El resultado del ejemplo sería:

0.2
Primer final.
Excepción recibida : División por cero.
Segundo final.
¡Hola mundo!

Ejemplo #4 Interacción entre el bloque finally y return

<?php

function test() {
try {
throw new
Exception('foo');
} catch (
Exception $e) {
return
'catch';
} finally {
return
'finally';
}
}

echo
test();
?>

El resultado del ejemplo sería:

finally

Ejemplo #5 Herencia de una excepción

<?php

class MyException extends Exception { }

class
Test {
public function
testing() {
try {
try {
throw new
MyException('foo!');
} catch (
MyException $e) {
// se relanza
throw $e;
}
} catch (
Exception $e) {
var_dump($e->getMessage());
}
}
}

$foo = new Test;
$foo->testing();

?>

El resultado del ejemplo sería:

string(4) "foo!"

Ejemplo #6 Gestión de excepciones de captura múltiple

<?php

class MyException extends Exception { }

class
MyOtherException extends Exception { }

class
Test {
public function
testing() {
try {
throw new
MyException();
} catch (
MyException | MyOtherException $e) {
var_dump(get_class($e));
}
}
}

$foo = new Test;
$foo->testing();

?>

El resultado del ejemplo sería:

string(11) "MyException"

Ejemplo #7 Omitir la variable atrapada

Solo permitido en PHP 8.0.0 y posteriores.

<?php

function test() {
throw new
SpecificException('Oopsie');
}

try {
test();
} catch (
SpecificException) {
print
"Se lanzó una SpecificException, pero no nos importan los detalles.";
}
?>

El resultado del ejemplo sería:

Se lanzó una SpecificException, pero no nos importan los detalles.

Ejemplo #8 Throw como expresión

Solo permitido en PHP 8.0.0 y posteriores.

<?php

class SpecificException extends Exception {}

function
test() {
do_something_risky() or throw new Exception('No funcionó');
}

function
do_something_risky() {
return
false; // Simular un fallo
}

try {
test();
} catch (
Exception $e) {
print
$e->getMessage();
}
?>

El resultado del ejemplo sería:

No funcionó
add a note

User Contributed Notes 13 notes

up
129
ask at nilpo dot com
15 years ago
If you intend on creating a lot of custom exceptions, you may find this code useful. I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes. It also properly pushes all information back to the parent constructor ensuring that nothing is lost. This allows you to quickly create new exceptions on the fly. It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
/* Protected methods inherited from Exception class */
public function getMessage(); // Exception message
public function getCode(); // User-defined Exception code
public function getFile(); // Source filename
public function getLine(); // Source line
public function getTrace(); // An array of the backtrace()
public function getTraceAsString(); // Formated string of trace

/* Overrideable methods inherited from Exception class */
public function __toString(); // formated string for display
public function __construct($message = null, $code = 0);
}

abstract class
CustomException extends Exception implements IException
{
protected
$message = 'Unknown exception'; // Exception message
private $string; // Unknown
protected $code = 0; // User-defined exception code
protected $file; // Source filename of exception
protected $line; // Source line of exception
private $trace; // Unknown

public function __construct($message = null, $code = 0)
{
if (!
$message) {
throw new
$this('Unknown '. get_class($this));
}
parent::__construct($message, $code);
}

public function
__toString()
{
return
get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
. "{$this->getTraceAsString()}";
}
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
try {
throw new
TestException();
}
catch (
TestException $e) {
echo
"Caught TestException ('{$e->getMessage()}')\n{$e}\n";
}
catch (
Exception $e) {
echo
"Caught Exception ('{$e->getMessage()}')\n{$e}\n";
}
}

echo
'<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
up
13
tianyiw at vip dot qq dot com
1 year ago
Easy to understand `finally`.
<?php
try {
try {
echo
"before\n";
1 / 0;
echo
"after\n";
} finally {
echo
"finally\n";
}
} catch (
\Throwable) {
echo
"exception\n";
}
?>
# Print:
before
finally
exception
up
77
Johan
13 years ago
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start
();
try {
/*contains all page logic
and throws error if needed*/
...
} catch (
Exception $e) {
ob_end_clean();
displayErrorPage($e->getMessage());
}
?>
up
8
jlherren
1 year ago
As noted elsewhere, throwing an exception from the `finally` block will replace a previously thrown exception. But the original exception is magically available from the new exception's `getPrevious()`.

<?php
try {
try {
throw new
RuntimeException('Exception A');
} finally {
throw new
RuntimeException('Exception B');
}
}
catch (
Throwable $exception) {
echo
$exception->getMessage(), "\n";
// 'previous' is magically available!
echo $exception->getPrevious()->getMessage(), "\n";
}
?>

Will print:

Exception B
Exception A
up
29
Edu
11 years ago
The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
try {
throw new
\Exception("Hello");
} catch(
\Exception $e) {
echo
$e->getMessage()." catch in\n";
throw
$e;
} finally {
echo
$e->getMessage()." finally \n";
throw new
\Exception("Bye");
}
} catch (
\Exception $e) {
echo
$e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally
Bye catch out
up
24
Shot (Piotr Szotkowski)
16 years ago
‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).
up
14
christof+php[AT]insypro.com
7 years ago
In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

<?php
set_error_handler
(function($errno, $errstr, $errfile, $errline){
if(
$errno === E_WARNING){
// make it more serious than a warning so it can be caught
trigger_error($errstr, E_ERROR);
return
true;
} else {
// fallback to default php error handler
return false;
}
});

try {
// code that might result in a E_WARNING
} catch(Exception $e){
// code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
} finally {
restore_error_handler();
}
?>
up
15
daviddlowe dot flimm at gmail dot com
7 years ago
Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

<?php

try {
throw new
Error( "foobar" );
// or:
// throw new Exception( "foobar" );
}
catch (
Throwable $e) {
var_export( $e );
}

?>
up
16
Simo
10 years ago
#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.
up
16
telefoontoestel at nospam dot org
10 years ago
When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.

<?php
try {
echo
"try block<br />";
throw new
Exception("test");
} catch (
Exception $ex) {
echo
"catch block<br />";
} finally {
echo
"finally block<br />";
}

// try block
// catch block
// finally block
?>

<?php
try {
echo
"try block<br />";
throw new
Exception("test");
} catch (
Exception $ex) {
echo
"catch block<br />";
exit(
1);
} finally {
echo
"finally block<br />";
}

// try block
// catch block
?>
up
11
mlaopane at gmail dot com
7 years ago
<?php

/**
* You can catch exceptions thrown in a deep level function
*/

function employee()
{
throw new
\Exception("I am just an employee !");
}

function
manager()
{
employee();
}

function
boss()
{
try {
manager();
} catch (
\Exception $e) {
echo
$e->getMessage();
}
}

boss(); // output: "I am just an employee !"
up
9
Tom Polomsk
10 years ago
Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.
up
9
Sawsan
13 years ago
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name
= "Name";

//check if the name contains only letters, and does not contain the word name

try
{
try
{
if (
preg_match('/[^a-z]/i', $name))
{
throw new
Exception("$name contains character other than a-z A-Z");
}
if(
strpos(strtolower($name), 'name') !== FALSE)
{
throw new
Exception("$name contains the word name");
}
echo
"The Name is valid";
}
catch(
Exception $e)
{
throw new
Exception("insert name again",0,$e);
}
}

catch (
Exception $e)
{
if (
$e->getPrevious())
{
echo
"The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
}
echo
"The Exception is: ".$e->getMessage()."<br/>";
}

?>
To Top