Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Error Handling

Proper error handling makes your application robust and user-friendly. PHP provides error levels, custom error handlers, and exception handling via try-catch.

Error Types and error_reporting()

PHP has several error levels. Use error_reporting() to control which errors are shown.

Error Reporting
<?php
// Error levels:
// E_ERROR   — fatal, stops execution
// E_WARNING — non-fatal, script continues
// E_NOTICE  — minor issues (undefined variable)
// E_DEPRECATED — deprecated feature used
// E_ALL     — all errors

// Development: show all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Production: log errors, don't display
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php_errors.log');

// Custom error handler
function myErrorHandler(int $errno, string $errstr,
                        string $errfile, int $errline): bool {
    echo "<b>Error [$errno]</b>: $errstr in $errfile on line $errline";
    return true; // don't execute PHP's internal error handler
}
set_error_handler("myErrorHandler");

// Trigger a notice
echo $undefinedVar; // triggers E_NOTICE
?>

try-catch-finally and Exceptions

Use exceptions for recoverable errors. The finally block always runs regardless of whether an exception was thrown.

try-catch-finally
<?php
function divide(int $a, int $b): float {
    if ($b === 0) {
        throw new InvalidArgumentException("Division by zero");
    }
    return $a / $b;
}

try {
    echo divide(10, 2);  // 5
    echo divide(10, 0);  // throws exception
} catch (InvalidArgumentException $e) {
    echo "Caught: " . $e->getMessage();
    echo " in " . $e->getFile() . " line " . $e->getLine();
} catch (Exception $e) {
    echo "General error: " . $e->getMessage();
} finally {
    echo "This always runs (cleanup code here)";
}
?>

Custom Exception Classes

Custom Exceptions
<?php
// Custom exception classes
class DatabaseException extends RuntimeException {}
class ValidationException extends RuntimeException {
    private array $errors;

    public function __construct(array $errors, string $message = "") {
        parent::__construct($message ?: implode(", ", $errors));
        $this->errors = $errors;
    }

    public function getErrors(): array {
        return $this->errors;
    }
}

function validateAge(int $age): void {
    if ($age < 0 || $age > 150) {
        throw new ValidationException(
            ["Age must be between 0 and 150"],
            "Validation failed"
        );
    }
}

try {
    validateAge(200);
} catch (ValidationException $e) {
    echo $e->getMessage() . "\n";
    print_r($e->getErrors());
} catch (DatabaseException $e) {
    echo "DB Error: " . $e->getMessage();
}
?>

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.