135

In regards to Error handling in PHP -- As far I know there are 3 styles:

  1. die()or exit() style:

    $con = mysql_connect("localhost","root","password");
    
    if (!$con) {
     die('Could not connect: ' . mysql_error());
    }
    
  2. throw Exception style:

     if (!function_exists('curl_init')) {
    
          throw new Exception('need the CURL PHP extension. 
                               Recomplie PHP with curl');
        }
    
  3. trigger_error() style:

    if(!is_array($config) && isset($config)) {
            trigger_error('Error: config is not an array or is not set', E_USER_ERROR);
        }
    

Now, in the PHP manual all three methods are used.

  • What I want to know is which style should I prefer & why?

  • Are these 3 drop in replacements of each other & therefore can be used interchangeably?

Slightly OT: Is it just me or everyone thinks PHP error handling options are just too many to the extent it confuses php developers?

2
  • 7
    These are not "styles". They are different language features. For different purposes. Commented Aug 15, 2011 at 8:54
  • 12
    @mario: what are different indented purpose? Please enlighten me :) Commented Aug 15, 2011 at 9:00

2 Answers 2

98

The first one should never be used in production code, since it's transporting information irrelevant to end-users (a user can't do anything about "Cannot connect to database").

You throw Exceptions if you know that at a certain critical code point, your application can fail and you want your code to recover across multiple call-levels.

trigger_error() lets you fine-grain error reporting (by using different levels of error messages) and you can hide those errors from end-users (using set_error_handler()) but still have them be displayed to you during testing.

Also trigger_error() can produce non-fatal messages important during development that can be suppressed in production code using a custom error handler. You can produce fatal errors, too (E_USER_ERROR) but those aren't recoverable. If you trigger one of those, program execution stops at that point. This is why, for fatal errors, Exceptions should be used. This way, you'll have more control over your program's flow:

// Example (pseudo-code for db queries):

$db->query('START TRANSACTION');

try {
    while ($row = gather_data()) {
       $db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...);
    }
    $db->query('COMMIT');
} catch(Exception $e) {
    $db->query('ROLLBACK');
}

Here, if gather_data() just plain croaked (using E_USER_ERROR or die()) there's a chance, previous INSERT statements would have made it into your database, even if not desired and you'd have no control over what's to happen next.

Sign up to request clarification or add additional context in comments.

11 Comments

so out of trigger_error() & throwing exceptions: which one should I use & when?
@Gaurish See the added example on that.
After reading your example, I think now I understand the purpose behind throw exception better. Thanks :)
@Pacerier That depends on the server's configuration, actually. A system might be configured to autocommit per default, hence the explicit ROLLBACK. This pseudo-code example covers both cases: servers which aren't configured to autocommit (the COMMIT statement is required) and those that do.
@LinusKleen, isn't autocommit turned off once we run the line query('START TRANSACTION');?
|
13

I usually use the first way for simple debugging in development code. It is not recommended for production. The best way is to throw an exception, which you can catch in other parts of the program and do some error handling on.

The three styles are not drop-in replacements for each other. The first one is not an error at all, but just a way to stop the script and output some debugging info for you to manually parse. The second one is not an error per se, but will be converted into an error if you don't catch it. The last one is triggering a real error in the PHP engine which will be handled according to the configuration of your PHP environment (in some cases shown to the user, in other cases just logged to a file or not saved at all).

5 Comments

What happens when exception is thrown but not caught? it will cause a fatal error, I guess. And with trigger_error() same thing happens. so what's the difference?
The difference is that you can catch the exception and handle it in any way you want.
@EmilVikström But errors can also by catched by a custom error handler. Also since PHP7 errors and exception both based on the throwable interface. Since PHP8 there is also an class named Error. When I look into the class definition of this class and compared it with the Exception class the only difference was the class name. So I would assume that the Error class is a descendant of the Exception class. But I'm not sure.
Per the PHP manual: "Error is the base class for all internal PHP errors." "Exception is the base class for all user exceptions." Neither extends the other, though they both implement the Throwable interface.
@CuriousMind never throw an exception without catching it. Depending on the server settings which might or might not be under your control exceptions or trigger_errors might only be visible to the developer or hoster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.