PHP Error Handling and Debugging
# 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 thetry/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/catchblocks to handle Exceptions gracefully without crashing the script.
-
Use
vardump()andprintr()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
includefor 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):
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.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.
7. Real-World Examples
As seen in Chapter 21, connecting to a database usestry/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 thetry/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. Write a script with a deliberate syntax error (missing semicolon) and observe the PHP Fatal Error screen.
-
2.
Fix the error. Then create an array and use
vardump()inside<pre>tags to inspect it.
-
3.
Write a
try/catchblock 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:
Fixed Code (with explanations):
13. Coding Challenges
Challenge 1: Write a functioncheckAge($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 usingtry/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 multiplecatch 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 usingvardump() 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.