CHAPTER 13 ■ SPL EXCEPTIONS^191
the log. There is no need to close the file handle, as this will be done for you when the class is
torn down.
The data that is written is the __toString() method of the exception, which returns some basic
data, including the error message and call stack. For more complete data, use the var_export()
function and set its second parameter, $return, to true.
exception 'LogicException' with message 'Demo' in
listing2.php:7
Stack trace:
#0 {main}
-- var_export format –
LogicException::__set_state(array(
'message' => 'Demo',
'string' => '',
'code' => 0,
'file' => 'listing2.php',
'line' => 7,
'trace' =>
array (
),
))
So now that you know what to do with unspecific logic errors, what do you do when some-
thing goes wrong at runtime? The answer is RuntimeException.
Runtime Exceptions
RuntimeException is LogicException’s alter ego. It is designed to handle all things runtime.
class RuntimeException extends Exception
Like LogicException, RuntimeException is built upon by several specialization classes
defined by the SPL, as explained in the following sections. What’s left over becomes a standard
RuntimeException. A good example of this is a banking scenario, wherein two concurrent actions
cannot result in a negative account balance. Listing 13-3 shows this scenario.
Listing 13-3. Throwing RuntimeException
function purchase() {
//Begin transaction and acquire lock
//Check funds again to prevent race condition
if(checkSufficientFunds()) {
//Insert and commit transaction
McArthur_819-9C13.fm Page 191 Thursday, February 28, 2008 7:53 AM