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.
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} 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 ...