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 ...
Get Upgrading to PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.