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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access