Skip to main content
PHP for Beginners
CHAPTER 26 Beginner

PHP Error Handling and Debugging

Updated: May 12, 2026
20 min read

# Chapter 26: PHP Error Handling and Debugging

1. Introduction

Welcome to Chapter 26! Every developer writes bugs. It is an unavoidable part of programming. A missing semicolon, a failed database connection, or an undefined variable will cause your script to misbehave or crash. Knowing how to read error messages, handle expected failures gracefully, and debug your code efficiently is what separates a beginner from a professional. In this chapter, we will learn how to read PHP errors, use the try/catch block for Exception handling, and explore debugging techniques.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the different levels of PHP Errors (Notices, Warnings, Fatal Errors).
  • Enable and disable error reporting.
  • Use try/catch blocks to handle Exceptions gracefully without crashing the script.
  • Use vardump() and printr() effectively for debugging variables.

3. Types of PHP Errors

PHP has three main categories of errors you will encounter:
  • Notices: Minor issues. The script continues running. (e.g., Echoing a variable that hasn't been defined).
  • Warnings: Serious issues, but the script still continues. (e.g., Using include for a file that does not exist).
  • Fatal Errors: Critical issues. The script halts execution immediately. (e.g., Calling a function that doesn't exist, or a syntax error like a missing semicolon).

4. Error Reporting

During development, you want to see EVERY error. In production (on a live website), you want to hide EVERY error from the user (as they reveal sensitive server information) and log them to a file instead.

You can control this at the top of your script (or preferably in your php.ini file):

php
12345678910
<?php
// Display all errors (Use ONLY in development!)
ini_set(&#039;display_errors', 1);
ini_set(&#039;display_startup_errors', 1);
error_reporting(E_ALL);

// Example of a Warning
include &#039;missing_file.php'; 
echo "Script still running!";
?>

5. Exceptions and Try/Catch

While traditional errors are generated by the PHP engine, Exceptions are generated by object-oriented code (like PDO) when something fails. Unlike Fatal Errors, Exceptions can be "caught" and handled smoothly without crashing the entire script.
php
12345678910111213141516171819202122
<?php
function divideNumbers($a, $b) {
    if ($b == 0) {
        // We manually "throw" an Exception
        throw new Exception("Division by zero is mathematically impossible!");
    }
    return $a / $b;
}

// Handling the Exception
try {
    // Try to run this code
    echo divideNumbers(10, 0);
    echo "This line will not print if an exception is thrown.";
    
} catch (Exception $e) {
    // If it fails, catch the error and do something graceful
    echo "An error occurred: " . $e->getMessage();
}

echo "<br>The script continues running normally down here!";
?>

6. Debugging Basics

When a script isn't doing what you expect, but there is no error message, you have a logic bug. The best way to debug is to look inside your variables.
  • echo: Good for simple strings/numbers.
  • printr($array): Great for printing arrays in a readable format.
  • vardump($variable): The ultimate debugging tool. It outputs the variable type, length, and exact value.
  • die() / exit(): Stops the script immediately. Used to check the state of data at a specific line.
php
123456789
<?php
$user = ["name" => "John", "age" => 25];

echo "<pre>"; // Makes array output cleanly formatted
var_dump($user);
echo "</pre>";

die("Script stopped here for debugging.");
?>

7. Real-World Examples

As seen in Chapter 21, connecting to a database uses try/catch. If the database is offline, PDO throws a PDOException. If we didn't catch it, the user would see a raw, ugly Fatal Error exposing the database username. Because we catch it, we can display a nice HTML page saying "Maintenance Mode".

8. Output Explanations

In the try/catch example, the function divideNumbers(10, 0) hits the if statement and throws an Exception. Execution immediately jumps out of the try block and into the catch block. The $e variable catches the Exception object, allowing us to echo its message safely. The script then continues normally below the block.

9. Common Mistakes

  • Syntax Errors: Missing a semicolon ; or a closing bracket }. PHP will often say the error is on line 20, but the missing semicolon is actually at the end of line 19!
  • Displaying errors in production: Never leave iniset('displayerrors', 1); on a live site. Hackers will deliberately cause errors to read your file paths.
  • Empty Catch Blocks: Writing catch (Exception $e) { } and leaving it empty. The error is silenced, but the script is broken, making it impossible to debug why it's not working. Always log the error!

10. Best Practices

  • Develop with errorreporting(EALL); turned on so you catch Notices and Warnings before they become bigger problems.
  • Log production errors to a secure text file using errorlog("Error message");.

11. Exercises

  1. 1. Write a script with a deliberate syntax error (missing semicolon) and observe the PHP Fatal Error screen.
  1. 2. Fix the error. Then create an array and use vardump() inside <pre> tags to inspect it.
  1. 3. Write a try/catch block that connects to a non-existent MySQL database and gracefully echoes "Database Offline."

12. Mini Project: Debugging Exercise App

Task: Here is a broken piece of code. It tries to calculate an average, but throws notices and warnings. Use debugging tools to fix it.

Broken Code:

php
1234567891011
<?php
$grades = [80, 90, "A", 100];
$total = 0;

foreach ($grade in $grades) {
    $total = $total + $grade;
}

$average = $total / count($grade);
echo "Average is: " . $average;
?>

Fixed Code (with explanations):

php
12345678910111213141516171819202122232425
<?php
$grades = [80, 90, "A", 100];
$total = 0;
$valid_count = 0; // Need a counter for valid numbers

// Fix 1: Incorrect foreach syntax. It is $grades as $grade
foreach ($grades as $grade) {
    // Fix 2: Check if it's a number to avoid math errors on "A"
    if (is_numeric($grade)) { 
        $total += $grade;
        $valid_count++;
    }
}

// Fix 3: Prevent division by zero if array was empty
try {
    if ($valid_count == 0) {
        throw new Exception("No valid grades to calculate.");
    }
    $average = $total / $valid_count; // Fix 4: Divide by valid count, not count($grade)
    echo "Average is: " . $average;
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

13. Coding Challenges

Challenge 1: Write a function checkAge($age) that throws an Exception with the message "Too young" if the age is under 18. Wrap the function call in a try/catch block and echo the error message gracefully.

14. MCQs with Answers

1. Which type of PHP error halts the script execution immediately? A) Notice B) Warning C) Fatal Error D) Exception (if caught) *Answer: C*

2. What is the best debugging function to inspect the exact data type and value of an array? A) echo B) print C) vardump() D) debug() *Answer: C*

3. What block is required alongside a try block? A) catch B) else C) throw D) finally *Answer: A*

15. Interview Questions

Q: What is the difference between a PHP Error and an Exception? *A:* PHP Errors (Notices, Warnings, Fatal Errors) are traditionally generated by the PHP engine itself when it encounters problems (like syntax errors or missing files). Exceptions are an Object-Oriented concept. They are deliberately "thrown" by the code when an unexpected condition occurs and can be "caught" and handled gracefully by the developer using try/catch blocks, preventing script termination.

Q: Why shouldn't you display errors on a live production server? *A:* Displaying raw PHP errors to end-users exposes sensitive information about your server environment, such as absolute file paths, database usernames, or query structures. This information is highly valuable to attackers. Errors should be logged to a secure file instead.

16. FAQs

Q: Can I catch multiple different types of Exceptions? *A:* Yes! You can chain multiple catch blocks together. For example, you can catch a specific PDOException first to handle database errors, and follow it with a generic catch (Exception $e) to handle everything else.

17. Summary

You are now equipped to fix your own code! You learned how to interpret the difference between Notices, Warnings, and Fatal errors. You practiced using var
dump() to peer into the hidden state of your variables, and you mastered the elegant try/catch architecture to prevent your applications from crashing when the unexpected occurs.

18. Next Chapter Recommendation

Our PHP apps have been isolated, only talking to our own database. But what if we want to show live weather data or accept Stripe payments? In Chapter 27: PHP APIs and JSON, we will learn how to make PHP communicate with other servers across the internet!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·