W3docs

getCode()

Learn how the PHP Exception::getCode() method returns the integer code attached to an exception, with practical examples, custom exceptions, and common gotchas.

The PHP getCode() Method

When you catch an exception in PHP, you often need to know which error happened so you can react differently to each one. The Exception::getCode() method gives you exactly that: it returns the integer error code that was attached to the exception when it was created. This page covers what the code is, how to set and read it, how it behaves across the standard exception hierarchy, and the gotchas that trip people up.

If you are new to error handling, start with PHP exceptions and the try-catch statement, then come back here.

What the exception code is

Every PHP exception object carries three core pieces of information: a message (read with getMessage()), a line/file (read with getLine()), and a code. The code is a developer-defined value you pass as the second argument to the exception constructor:

new Exception(string $message = "", int $code = 0, ?Throwable $previous = null)

getCode() simply returns that second argument. It is a label you choose, not something PHP fills in automatically. If you do not pass a code, it defaults to 0.

Syntax

public Exception::getCode(): mixed
  • Parameters: none.
  • Return value: the code passed to the constructor. For the base Exception class this is an int (default 0).

Note: the return type is documented as mixed because ErrorException and some PDO exceptions use string codes (for example, SQLSTATE values). For a plain Exception, expect an integer.

Basic example

Here we throw an exception with the code 100, then read it back in the catch block:

<?php

try {
    throw new Exception("Database connection failed", 100);
} catch (Exception $e) {
    echo "Message: " . $e->getMessage() . "\n";
    echo "Code: " . $e->getCode() . "\n";
}

Output:

Message: Database connection failed
Code: 100

Notice that getCode() returns 100 — the value we passed — while getMessage() returns the text. The two are independent.

Branching on the code

The whole point of a code is to let one catch block route different errors to different handling. The codes below are arbitrary constants chosen for the application:

<?php

const ERR_DB        = 100;
const ERR_NOT_FOUND = 404;

function loadUser(int $id): string
{
    if ($id < 1) {
        throw new Exception("Invalid user id", ERR_NOT_FOUND);
    }
    // ...imagine a DB lookup that fails...
    throw new Exception("Could not reach the database", ERR_DB);
}

try {
    echo loadUser(0);
} catch (Exception $e) {
    switch ($e->getCode()) {
        case ERR_NOT_FOUND:
            echo "404: " . $e->getMessage();
            break;
        case ERR_DB:
            echo "500: " . $e->getMessage();
            break;
        default:
            echo "Unknown error: " . $e->getMessage();
    }
}

Output:

404: Invalid user id

Because we called loadUser(0), the $id < 1 check throws first with ERR_NOT_FOUND (404), so that case runs.

The default code is 0

If you create an exception without a code, getCode() returns 0, not null:

<?php

try {
    throw new Exception("Something went wrong");
} catch (Exception $e) {
    var_dump($e->getCode());
}

Output:

int(0)

This matters when you branch on the code: if ($e->getCode()) treats a missing code (0) as falsy, which is usually what you want, but be deliberate about it.

Custom exception classes

A common pattern is to bake the code into a dedicated exception class so callers never have to remember the magic number:

<?php

class HttpException extends Exception {}

class NotFoundException extends HttpException
{
    public function __construct(string $message = "Not Found")
    {
        parent::__construct($message, 404);
    }
}

try {
    throw new NotFoundException("User profile not found");
} catch (HttpException $e) {
    echo $e->getCode() . " " . $e->getMessage();
}

Output:

404 User profile not found

The NotFoundException constructor forwards 404 to parent::__construct(), so getCode() returns 404 even though the calling code never typed that number.

getCode() vs. getMessage() vs. getPrevious()

MethodReturnsUse it for
getCode()The integer code you passedBranching/logging by error type
getMessage()The human-readable messageShowing or logging what failed
getPrevious()The chained inner exception (or null)Preserving the original cause when re-throwing

These are complementary — most real handlers read all three.

Common gotchas

  • The code must be an integer for Exception. Passing a string (e.g. new Exception("x", "ABC")) throws a TypeError in modern PHP. Use a constant instead.
  • getCode() is not the HTTP status code. It is only a status code if you chose to store one there. PHP does nothing with the value itself.
  • Built-in exceptions rarely set a meaningful code. Most core PHP exceptions leave it at 0; don't rely on it being filled in unless you set it.
  • PDOException codes are SQLSTATE strings. When catching database errors, getCode() may return something like "42S02" (a string), which is why the return type is mixed.

Best practices

  1. Define named constants (or class-based exceptions) for codes instead of scattering raw numbers.
  2. Keep codes stable — other code and logs may depend on them.
  3. Log the code together with getMessage() and getLine() so failures are traceable.
  4. Don't expose internal codes or messages to end users; map them to safe, generic responses.

Conclusion

Exception::getCode() returns the integer code you attached when the exception was created, giving you a reliable, machine-readable way to distinguish one error from another. Pair it with getMessage() for human-readable detail, prefer named constants or custom exception classes over magic numbers, and remember that some exception types (like PDOException) use string codes.

Practice

Practice
What does the PHP Exception::getCode() method return?
What does the PHP Exception::getCode() method return?
Was this page helpful?