In PHP, Exception::getCode() returns the integer code stored in the exception. You set that code when you create the Exception, or leave the default value 0.
Codes are useful when your app groups errors, for example 404 for missing data or 500 for unexpected failures. The method is final. Note that some SPL exceptions historically returned other types, but Exception itself returns an int.
Syntax
Call getCode() with the values you need. Start with this line.
PHP
$code = $e->getCode();
Call
What it does
$e->getCode()
Returns the integer exception code.
(new Exception("x", 42))->getCode()
Reads the code 42 from a new Exception.
match ($e->getCode()) { 404 => "missing", default => "other" }
Branches on the code with match.
getCode() is final. For Exception the return type is int. Pass the code as the second constructor argument.
Library declarations
PHP
final public Exception::getCode(): int
Parameters
Parameter
Description
—
This method takes no parameters.
Return Value
Return Value
Description
int
The exception code. The default is 0 when you omit it in the constructor.
PHP Examples
Example 1 — Read a Custom Error Code
Throw an Exception with code 404 and print it from the catch block.