Skip to content

Handling errors in PHP

Using try-catch blocks for exception handling

Objective:

The objective of this lesson is to teach learners how to handle errors in PHP effectively. By the end of this lesson, participants should be able to:

  • Understand the types of errors in PHP.
  • Implement error handling mechanisms using try-catch blocks for exception handling.

Description:

1.1 Types of Errors in PHP

1.1.1 Syntax Errors

Syntax errors occur when the PHP parser encounters code that violates the language grammar rules. These errors prevent the script from running.

<?php
// Example of a syntax error
echo "Hello World"
?>

1.1.2 Runtime Errors

Runtime errors occur during script execution. They may include issues like division by zero, accessing undefined variables, or calling functions that don’t exist.

<?php
// Example of a runtime error
$undefinedVariable = $someUndefinedVariable;
?>

1.1.3 Logic Errors

Logic errors are subtle issues in the script’s logic that lead to unexpected behavior. The code runs without errors, but it doesn’t produce the desired results.

<?php
// Example of a logic error
$number1 = 10;
$number2 = 20;
$sum = $number1 * $number2; // Should be addition, not multiplication
echo "Sum: " . $sum;
?>

1.2 Error Handling Mechanisms

1.2.1 Displaying Errors

Discuss the error_reporting and display_errors directives in the PHP configuration. Explain how to configure these settings for development and production environments.

<?php
// Example of displaying errors in development
ini_set('display_errors', 1);
error_reporting(E_ALL);
?>

1.2.2 Custom Error Handling

Introduce custom error handlers using set_error_handler(). This allows developers to define their error-handling functions.

<?php
// Example of a custom error handler
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error: [$errno] $errstr in $errfile on line $errline";
}

// Set the custom error handler
set_error_handler("customErrorHandler");
?>

1.3 Exception Handling

1.3.1 Introduction to Exceptions

Explain the concept of exceptions in PHP. Exceptions are a way to handle errors that occur at runtime and may be recoverable.

<?php
// Example of throwing an exception
function divide($numerator, $denominator) {
    if ($denominator === 0) {
        throw new Exception("Cannot divide by zero");
    }
    return $numerator / $denominator;
}
?>

1.3.2 Try-Catch Blocks

Teach the use of try-catch blocks to handle exceptions gracefully. This allows developers to isolate error-prone code and handle exceptions in a structured manner.

<?php
// Example of try-catch blocks
try {
    $result = divide(10, 0);
    echo "Result: " . $result;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

1.4 Best Practices

1.4.1 Logging Errors

Discuss the importance of logging errors for debugging and monitoring. Introduce tools like error logs and log files.

<?php
// Example of logging errors to a file
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
?>

1.4.2 Graceful Error Messages

Encourage the use of user-friendly error messages for public-facing websites. Avoid exposing sensitive information and provide clear instructions for users.

<?php
// Example of graceful error messages
try {
    // Some code that may throw an exception
} catch (Exception $e) {
    echo "An unexpected error occurred. Please try again later.";
}
?>

1.5 Practice Exercise

Task:

  1. Syntax Error Handling:
    • Create a PHP script named syntax_error_example.php.
    • Introduce a deliberate syntax error (e.g., missing semicolon or unmatched parentheses).
    • Configure PHP to display syntax errors during development.
<?php
// syntax_error_example.php

// Deliberate syntax error
echo "Hello World"
?>

Runtime Error Handling:

  • Develop a PHP script named runtime_error_example.php.
  • Introduce a runtime error, such as attempting to divide by zero.
  • Implement a custom error handler named customErrorHandler that logs the error details to a file.
<?php
// runtime_error_example.php

// Set custom error handler
set_error_handler("customErrorHandler");

// Deliberate runtime error
$undefinedVariable = $someUndefinedVariable;

function customErrorHandler($errno, $errstr, $errfile, $errline) {
    // Log error details to a file
    $logMessage = "Error: [$errno] $errstr in $errfile on line $errline\n";
    error_log($logMessage, 3, '/path/to/error.log');
}
?>

Logic Error Handling:

  • Create a PHP script named logic_error_example.php.
  • Introduce a logic error (e.g., using the wrong operator in a calculation).
  • Use debugging techniques (e.g., var_dump or echo) to identify and fix the logic error.
<?php
// logic_error_example.php

// Deliberate logic error
$number1 = 10;
$number2 = 20;
$sum = $number1 * $number2; // Should be addition, not multiplication
echo "Sum: " . $sum;
?>
  1. xception Handling:
    • Create a PHP script named exception_handling_example.php.
    • Write a function named openFile that attempts to open a non-existent file.
    • Implement a try-catch block to handle the exception gracefully.
<?php
// exception_handling_example.php

// Function that throws an exception
function openFile($filename) {
    if (!file_exists($filename)) {
        throw new Exception("File not found: $filename");
    }

    // Logic to open and process the file (not relevant for this example)
}

// Try-catch block to handle the exception
try {
    openFile('nonexistent_file.txt');
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Additional Notes:

  • Ensure that the error.log file path in runtime_error_example.php is appropriate for your server environment.
  • Encourage learners to deliberately introduce errors, explore error messages, and practice debugging techniques.