O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

User Exceptions

Exceptions aren’t restricted to extensions. You can trigger your own exceptions by throwing an instance of the Exception class.

User-thrown exceptions are useful because they allow you to integrate the error handling for your own errors with exceptions thrown by PHP. Inside your methods, you may still need to check a return value; however, converting those errors into exceptions allows the developer using your classes to know he can reliably trap all errors using a try/catch block.

This section covers when it’s appropriate to throw exceptions of your own, and also how to create and throw an exception. Chapter 10 contains an address book application that demonstrates, among other things, how to put these exception-handling techniques into practice.

When to Use Exceptions

There many categories of errors, and exceptions are not always an appropriate way to handle them in PHP. In general, there are three major groups:

Programming errors

You, the programmer, have made a mistake. For instance, you passed an incorrect number of arguments to a method.

Client code errors

Your code is okay, but there’s a problem with an external resource. For instance, your code uses an XML file from a third-party web site, but that file isn’t valid XML. Or, a person has tried to join your site, but has requested a username already in use.

Resource failures

Your code is failing because of a breakdown in communication with another process. For instance, you cannot connect to a third-party web ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required