PHP Code Examples

Handle Exceptions and Log Errors in PHP

Use try/catch/finally to handle expected failures while keeping sensitive diagnostics out of visitor-facing responses.

Example

<?php
try {
    $stmt = $pdo->prepare(
        'SELECT id, title FROM articles WHERE id = :id'
    );
    $stmt->execute(['id' => $articleId]);

    $article = $stmt->fetch();

    if (!$article) {
        http_response_code(404);
        exit('Article not found.');
    }
} catch (PDOException $exception) {
    error_log('Article query failed: ' . $exception->getMessage());

    http_response_code(500);
    exit('Something went wrong. Please try again later.');
}

Production configuration

Disable display_errors and enable log_errors in production. Store logs outside the public web root and restrict access to them.

Catch exceptions where you can take a meaningful recovery action. Avoid empty catch blocks that hide failures.

Share this page Help other developers discover this resource.