Error Handling in PHP

Error Handling in PHP

May 14, 2023

Error handling is a fundamental aspect of writing reliable and maintainable PHP code. Handling errors effectively helps you build robust applications that can gracefully respond to unexpected conditions.

Basics of PHP Error Handling:

PHP has multiple mechanisms for handling errors:

Error Reporting: PHP has various error reporting levels to identify and handle errors. These are set using the error_reporting() function or the error_reporting directive in php.ini.

  • E_ERROR: Fatal runtime errors. These errors halt script execution.

Example:

echo "Before error\n";
require("nonexistentfile.php"); // This file is not found.
echo "After error\n";  // This will not get printed.
  • E_WARNING: Non-fatal runtime errors. Execution continues.

Example:

echo "Before warning\n";
include("nonexistentfile.php"); // This file does not exist.
echo "After warning\n";  // This will get printed.
  • E_PARSE: Compile-time errors generated by the parser.E_PARSE errors are detected before the script starts running. This means if you have a parse error, none of your script will execute, not even the parts before the error.

  1. Custom Error Handlers: Using set_error_handler(), you can define a custom function to process errors. This function can then decide how to respond to each error type.
  2. Exceptions: Introduced in PHP 5, exceptions are a more modern way to handle errors. They can be "thrown" and "caught" using try, catch, and finally constructs.

Examples:

Simple Error Reporting

<?php
// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

Custom Error Handling

<?php
function customError($errno, $errstr) {
    echo "Custom error: [$errno] $errstr<br>";
}

// Set the error handler
set_error_handler("customError");

// Trigger an error
echo($test); // This will call our customError() function because $test is undefined
?>

Exceptions

<?php
function checkNum($number) {
    if ($number > 1) {
        throw new Exception("Number must be 1 or below");
    }
    return true;
}

try {
    checkNum(2);
    echo "If you see this, the number is 1 or below";
} catch (Exception $e) {
    echo "Message: " . $e->getMessage();
}
?>

Tips:

  1. Understand the difference: While both errors and exceptions can disrupt the normal flow of the program, errors are generally considered serious problems that a developer probably shouldn't try to recover from. Exceptions, on the other hand, can often be handled gracefully.
  2. Be aware of the finally block: In PHP 5.5 and newer, there's a finally block that can be used after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception was thrown or not.
  3. Use Exceptions judiciously: It's not always the right answer to wrap every piece of code in a try-catch block. Exceptions should be reserved for exceptional conditions, and not for regular error handling.
  4. Custom Exceptions: PHP allows you to create custom exception classes, extending the built-in Exception class, to handle specific error types more effectively.
  5. Logging is vital: Whenever an error or exception is caught, it's generally a good practice to log the details, which can later help in debugging.