Alex Rivera | Logout

In PHP5, should I use Exceptions or trigger_error/set_error_handler?

Asked 2008-09-13T15:18:54.423
32

What are the pros/cons of doing either way. Is there One Right Way(tm) ?

Edit
Report

1 Answer

20

If you want to use exceptions instead of errors for your entire application, you can do it with ErrorException and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an E_NOTICE will halt your entire application if your error_reporting settings do not suppress them.

In my opinion, there are several benefits to using ErrorException:

  1. A custom exception handler will let you display nice messages, even for errors, using set_exception_handler.
  2. It does not disrupt existing code in any way... trigger_error and other error functions will still work normally.
  3. It makes it really hard to ignore stupid coding mistakes that trigger E_NOTICEs and E_WARNINGs.
  4. You can use try/catch to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the @ error suppression hack:

    try {
        $foo = $_GET['foo'];
    } catch (ErrorException $e) {
        $foo = NULL;
    }
    
  5. You can wrap your entire script in a single try/catch block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.)

answered 2009-07-15T02:51:27.953

Your Answer