Forum Moderators: coopster

Message Too Old, No Replies

PHP5 Exception handling - only user thrown Exceptions are caught?

Different to other languages?

         

penders

4:26 pm on Sep 1, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've been used to using the Exception handling methodology in other languages. So I thought I'd apply the same principles to handle some error checking in PHP5. Only it doesn't work how I'd hoped; only user thrown Exceptions are caught?! Warnings and Fatal Errors don't get caught. This seems rather half-baked to me; or am I missing something?

For instance...

try { 
$myvar = 5 / 0;
throw new Exception('Stop here!');
} catch (Exception $e) {
echo 'EXCEPTION TRAPPED: '.$e->getMessage();
}

I would have expected the division by zero to be caught, but it doesn't.

Is this as expected?

eelixduppy

5:14 pm on Sep 1, 2008 (gmt 0)



From what I know, I don't think those types of errors throw exceptions and that PHP only catches exceptions that are thrown within code. For example, if you had a function that went to divide by zero, you can make it throw an exception instead of a fatal error:

function divide($a, $b) {
if(!$b)
throw new Exception("Division by zero");
else return $a/$b;
}

So basically, unless it's user-defined, I'm pretty sure PHP doesn't throw exceptions on it's own, otherwise you'd get a lot of fatal errors with uncaught exceptions.

cameraman

6:55 pm on Sep 1, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Looks like you could use set_error_handler [us.php.net] to throw them yourself.

coopster

6:13 pm on Sep 2, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



... and/or set_exception_handler [php.net]
See also: Exceptions [php.net]

pinterface

11:54 pm on Sep 2, 2008 (gmt 0)

10+ Year Member



The thing to remember is Errors are not Exceptions, at least not in PHP.

try-catch blocks also won't catch errors you throw via trigger_error. As has been mentioned, you could use set_error_handler to throw exceptions yourself. Specifically, see the ErrorException class [us.php.net] which provides an example of how to do this.