If you kill your scripts with ‘die’ or ‘exit’ your script instantly becomes less flexible.
Why not throw an Exception and let it bubble to the top? The script will terminate anyway, but provides better error reporting & gives you a chance to handle the error more gracefully. There is barely ever a time you want to simply kill your script.
Consider the following snippet, typical of many web applications (edit from objects & error handling answer on stackoverflow)
class DatabaseConnectionException extends Exception {} class Database { public function connect($user, $pass, $db) { //Connection stuff. //Assume we failed with a bad username. $baduser = true; if($baduser) { throw new DatabaseConnectionException('Username (' . $user. ') is invalid.'); } if($badpass) { // etc } } } $db = new Database(); $user = 'Maynard James Keenan'; $pass = '46and2'; try { $db->connect($user, $pass, $db); } catch (DatabaseConnectionException $e) { die("I cannot connect to the database"); }
Think of others when you die.
If you are working on a project and it suddenly stops and tells you:
“I cannot connect to the database.”
What useful information does this tell me? What database? Where? Why wasn’t it found? Is it trying to connect to the same database I’ve been working with? To figure out what’s going on, I have to grep for the error message, which I then discover is inside a die() then start putting in random echo, debug_print_backtrace, etc calls in the code to figure out what went wrong, why and where.
We could make this better by adding some additional debugging context information as the parameter for die…
die('I cannot connect to the database:' . $e);
But this still doesn’t tell us a whole heap and really depends on what information our programmer has deemed us worthy enough to receive from the exception call. While this is fine for simple cases, when it gets a bit more complex (eg an error is introduced futher up the call stack) in come the backtraces and echos.
Let’s say this was going on a production site. What happens if the db goes offline for some reason? Our end users are going to see some pretty ugly messages.
Secondly, if someone else is using your code and wants to adjust how that error is handled, (eg figures out a way the error can be recovered from)… all they need to do is try/catch the error.
Thirdly, You get control over what happens when the exception is thrown by setting up an exception handler with set_exception_handler. Maybe down the track you don’t want this to die, or you’d prefer your script to terminate on a pretty “Oops, something went wrong” page for the user. Not easily done done when your code is littered with die() statements. Don’t be scared to just not catch exceptions... unless of course you can do something useful with it (eg recover, or formulate a quality error message). Other than the speed for hacking some debugging only statements, I can’t see any benefit of using any die() statements anywhere in your project.