PHP 8.4.2 Released!

Exception::getCode

(PHP 5, PHP 7, PHP 8)

Exception::getCodeObtiene el código de una excepción

Descripción

final public Exception::getCode(): int

Devuelve el código de una excepción.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el código de Excepción en forma de int en Exception pero posiblemente en forma de otros tipos en Exception descendientes (por ejemplo como string en PDOException).

Ejemplos

Ejemplo #1 Ejemplo de Exception::getCode()

<?php
try {
throw new
Exception("Un mensaje de error", 30);
} catch(
Exception $e) {
echo
"El código de excepción es: " . $e->getCode();
}
?>

El resultado del ejemplo sería algo similar a:

El código de excepción es: 30

Ver también

add a note

User Contributed Notes 3 notes

up
76
talksonweb at gmail dot com
11 years ago
The exception code can be used to categorize your errors. If you're wondering what the exception code can be used for, read on below.

Let's say each time your application isn't able to connect to the database, you can save the error message under the error/exception code 214. At the end of the month, you can do a quick search on the error number '214' and find out how many times this error occurred. This makes life easier. Also, the error/exception message will give you details into what happened.

The point is to use both the exception message and code. It's helpful in the long run.

Note: I added this note, because I was confused earlier as to the purpose of the exception code and it's use.
up
29
ricky at rocker dot com
11 years ago
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0

<?php
try {
throw new
Exception("no code!!");
} catch (
Exception $e) {
print(
"Code='" . $e->getCode() . "'");
}
?>

outputs

Code='0'
up
8
2M
3 years ago
Do not use the strict operator as suggested when checking the Exception Code in \PDOException.
As per documentation: \PDOException is returning a string for its Exception Code and not an Integer.

Ran into the following in PHP8:
<?php

catch(\PDOException $e) {
var_dump($e->getCode()); //Output: string(5) "23000"
}

?>
To Top