Mistakes are inevitable, in life, programming, and application submissions. You can prepare for errors by making sure your application is designed to respond to them. This two-part article explains how PHP handles errors. It is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Even if you wear an S on your chest when it comes to programming, you can be sure that errors will creep into all but the most trivial of applications. Some of these errors are programmer-induced—they are the result of mistakes made during the development process. Others are user-induced, caused by the end user’s unwillingness or inability to conform to application constraints. For example, the user might enter 12341234 when asked for an e-mail address, obviously ignoring what would otherwise be expected as valid input. Yet regardless of the source of the error, your application must be able to encounter and react to such unexpected errors in a graceful fashion, hopefully doing so without losing data or crashing the application. In addition, your application should be able to provide users with the feedback necessary to understand the reason for such errors and potentially adjust their behavior accordingly.
This chapter introduces several features PHP has to offer for handling errors. Specifically, the following topics are covered:
Configuration directives: PHP’s error-related configuration directives determine the bulk of the language’s error-handling behavior. Many of the most pertinent directives are introduced in this chapter.
Error logging: Keeping a running log is the best way to record progress regarding the correction of repeated errors, as well as quickly identify newly introduced problems. In this chapter, you learn how to log messages to both your operating system syslog and a custom log file.
Exception handling: Prevalent among many popular languages (Java, C#, and Python, to name a few), exception handling was added to PHP with the version 5 release. Exception handling offers a standardized process for detecting, responding to, and reporting errors.
Historically, the development community has been notoriously lax in implementing proper application error handling. However, as applications continue to grow increasingly complex and unwieldy, the importance of incorporating proper error-handling strategies into your daily development routine cannot be overstated. Therefore, you should invest some time becoming familiar with the many features PHP has to offer in this regard.