Dutch PHP Conference 2023 - Call for Papers


(PHP 5, PHP 7, PHP 8)

Exception::getCodeПолучает код исключения


final public Exception::getCode(): int

Возвращает код исключения.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает код исключения типа int у класса Exception, но у потомков класса Exception может быть другой тип (например, типа string в PDOException).


Пример #1 Пример использования Exception::getCode()

try {
throw new
Exception("Какое-нибудь сообщение об ошибке", 30);
} catch(
Exception $e) {
"Код исключения: " . $e->getCode();

Результатом выполнения данного примера будет что-то подобное:

Код исключения: 30

Смотрите также

add a note

User Contributed Notes 4 notes

talksonweb at gmail dot com
9 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.
ricky at rocker dot com
10 years ago
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0

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


1 year 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:

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

ahmad dot mayahi at gmail dot com
6 years ago
One of the most useful tricks of getCode is handling duplication entries when trying to add a duplicate row into the database.

Sometimes we don't need to show any errors regarding this duplication.

The following snippet is taken from one of my projects:

//I have a mysql table called hosts with one unique key named host_name.
try {
$hosts = new Hosts(["host_name" => "www.example.com");
} catch (\
PDOException $e) {
      if (
$e->getCode() === 23000) {
//Do nothing

Here I'm saving the host name, and I don't care if it's already exists.
To Top