views:

371

answers:

2

I was wondering if it's considered a bad practice to globally convert all PHP Errors to Exceptions. Something like the following would be used:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    return false;
}

I suppose the assumption is that you can just start using "try/catch" around certain pieces of code that would normally throw Errors.

If it's not a case of Good/Bad, what are some of the Gotchas that could arise from this practice?

+1  A: 

Unfortunately, this won't work on fatal/parse/etc. errors...

Don't remember exactly, but I've tried this and in some cases got a message like "can't throw exception without workaround..." but I can't remember the conditions to get this result. But now I use this way and completely satisfied.

Jet
This answer seems to most understand the question, at least as of the time of it's acceptance. I despise answering my own questions, but I might be back later.
anonymous coward
A: 

Use exceptions for things that are truely beyond your control.

Good:

try {
   if (fopen('file.txt', 'w') === false) {
      throw new Exception('File could not be opened for write access.');
   }
} catch (Exception $e) {
   echo $e->getMessage();
}

Bad:

try {
   if (strlen($_POST['username']) < 5) {
      throw new Exception('Username too short');
   }
} catch (Exception $e) {
   echo $e->getMessage();
}

The first way is good because it occurs when its something that the user or the application cant control. It cant open the file because? could be many reasons.

The second way is an overkill use of try /catch when you should use trigger_error. The second way is down to the user not knowing the rules of the username validation.

In short use exceptions when you cant control what your testing. Remember exceptions have more overhead then trigger_error aswell :)

Ozzy
Usually there are errors which we want only to display for user, and errors which should be logged, showing to user only smth. like this "Internal error #123. Please, contact support.". In this model exception classes are quite formalized to achieve this result. So, the 1st example should be logged, but 2nd only for user and they should be ie. SystemException and UserException... Well, not sure if 2nd exapmle is "overkill use".
Jet
it may not seem like overkill at first but then you have to think about performance issues. An object is created every time an exception occurs. While that in itself is not slow, its no where near as fast as calling something like trigger_error. and the second example does not need a try catch. Just adds to overhead and when a page like this receives thousands of hits per day, the performance loss is noticable :)I personally never use try catch because i dont see the use for it.
Ozzy