7.3 System Exceptions

In contrast to some languages, notably Python and Java, PHP 5 doesn't throw exceptions whenever there's a problem. In fact, it never throws exceptions when you're using a procedural function. Instead, exceptions are strictly reserved for objects.

Furthermore, even when you're using an object, PHP throws exceptions only in two instances:

  • Errors in constructors

  • "Serious" problems in some extensions

These are the two instances when you must place your code inside a try/catch or risk a fatal error.

7.3.1 Constructors

Whenever there's an error during object instantiation, PHP throws an exception to signal failure. It must throw an exception because a constructor always returns an object, so it cannot return false or another value to indicate that it couldn't properly create an object.

You've already seen one example of a constructor throwing an exception back in Example 7-3. When you pass DOMElement an illegal tag name, DOMElement throws an exception.

A non-DOM example is the SQLite extension, which issues an exception when you don't provide a database name:

try {

    $db = new SQLiteDatabase( );

} catch (Exception $e) {

    print $e;


exception 'SQLiteException' with message 'SQLiteDatabase::_ _construct( ) expects at least

 1 parameter, 0 given' in /www/www.example.com/sqlite.php:2

Stack trace:

#0 {main} 

7.3.2 Serious Problems

In PHP 5, extensions throw exceptions only when there's serious logic error. Other errors are still returned in the traditional manner, by returning a designated error value such as false or -1.

There's no cut-and-dry definition of "serious." It varies from extension to extension, depending on the circumstances. Some extensions, such as DOM, throw exceptions in accordance with the DOM specification, which defines those instances as follows:

DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable). In general, DOM methods return specific error values in ordinary processing situations.

In contrast, other extensions, such as MySQLi and SQLite, never throw exceptions (except in their constructors).

Because the decision of if and when to throw exceptions is left up to the extension developer, there's no rule of thumb to determine whether a given method will or will not issue an exception. The only way to know how an extension behaves is to read its documentation in the PHP Manual (http://www.php.net/manual/).