SyntaxStudy
Sign Up
PHP Exception Messages and Codes
PHP Intermediate 4 min read

Exception Messages and Codes

Exception Messages and Codes

The Exception constructor accepts a message string, a numeric code, and a previous exception for chaining. These help with logging and error identification.

Example
<?php
try {
    throw new RuntimeException("Database connection failed", 503);
} catch (RuntimeException $e) {
    echo $e->getMessage();   // "Database connection failed"
    echo $e->getCode();      // 503
    echo $e->getFile();      // Path to the file
    echo $e->getLine();      // Line number
    echo $e->getTraceAsString(); // Stack trace

    // For API responses
    http_response_code($e->getCode());
    echo json_encode(["error" => $e->getMessage()]);
}
Pro Tip

Use HTTP status codes as exception codes for API exceptions — makes it easy to map exceptions to HTTP responses.