Chapter 12. Error Handling

The best laid plans of mice and men often go awry.

adapted from Robert Burns

If you work in programming or software development, you’re probably very familiar with bugs and the process of debugging. You might have even spent as much time, if not more, tracking down bugs as you do writing code in the first place. It’s an unfortunate maxim of software—no matter how hard a team works to build correct software, there will inevitably be a failure that needs to be identified and corrected.

Luckily, PHP makes finding bugs relatively straightforward. The forgiving nature of the language often also renders a bug a nuisance rather than a fatal flaw.

The following recipes introduce the quickest and easiest way to identify and handle bugs in your code. They also detail how to both code and handle custom exceptions thrown by your code in the event of invalid data output by a third-party API or other incorrect system behavior.

12.1 Finding and Fixing Parse Errors

Problem

The PHP compiler has failed to parse a script within your application; you want to find and correct the problem quickly.

Solution

Open the offending file in a text editor and review the line called out by the parser for syntax errors. If the problem isn’t immediately apparent, walk backwards through the code one line at a time until you find the problem and make corrections in the file.

Discussion

PHP is a relatively forgiving language and will often attempt to let even an incorrect or problematic ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.