The “do X or die()” pattern must die

July 28, 2010 – 6:33 pm Tags: , ,

What’s the most common pattern for error handling you see in beginner’s PHP code? – That’s right, do_X() or die('do_X failed);.

That’s nice and all, as at least you have some sort of error handling, but I think this way of handling errors must go. There is no place for it in modern PHP code – it’s the worst way to handle errors, not much better than not handling them at all.

Background

So you are a newbie and want to learn how to do MySQL in PHP.

Okay, let’s do a google search: PHP MySQL tutorial

I’ll let you guess how many of the first 10 use “or die()” to catch failing queries.

One?

Nope.

Five?

Nope.

All ten of them use “or die”! (and some even use the evil error eating @ operator)

So is it any wonder why it is so common?

If you’re a beginner, I’m not blaming you – how could you know of a better way if everything you can find talks about the bad way to do it?

How hard can it be to do error handling properly?

Never use die()

So why is die() so bad?

For starters, it may be a decent approach. However, when the size of the codebase grows, it becomes more and more difficult to locate problems.

If your code dies, you won’t know the line. You won’t know the function, and not the file. You won’t be able to graciously handle the error either – The application will just stop right there, right then.

There are two other approaches that are better:

  • trigger_error (or user_error)
  • Exceptions

trigger_error

trigger_error is, in a way, the next step from die(). Despite being the obvious next step, it’s still a much better approach.

  1. You’ll get better output: Not only will it show you the line number, it will tell you the filename too, so you know where to look. Even better, if you have Xdebug, you’ll get stack traces and other useful information.
  2. You will actually get output in the error log from this one.
  3. You can “catch” errors triggered by code using set_error_handler. This will allow you to maybe automatically display a nice “oops something went wrong” type of page or other such stuff

And perhaps also good is that you can use trigger_error in a very similar fashion as die:
do_X() or trigger_error('I have a boo boo', E_USER_ERROR);

This makes it very easy to make the jump to better error handling, and it can even be done with relative ease with an automatic search and replace.

Exceptions

Exceptions are in my opinion the way to handle errors.

  1. Exceptions are flexible: You can have use the standard exceptions or create custom ones to better describe the error.
  2. They can convey extra information: A custom exception class can, for example, include additional fields – it is an object afterall
  3. Using a try-catch block, you can easily handle exceptions on a case-by-case basis, making it easy to choose how to recover from specific exceptions.

Of course, the benefits mentioned for trigger_error also apply: Uncaught exceptions will provide good output (and better with Xdebug) and will cause output in the error log.

The only downside of using exceptions is that it’ll make your code a little more verbose. Except I lied when I said it’s a downside – more verbose code can be a good thing too.

Conclusion

Stop using or die() to handle errors.

Using either of the approaches mentioned here is much, much better. You’ll get output that makes it much easier to debug your code, the error log will actually become useful and you can handle your error cases much better in code, so that the application will not crap on the user.

You have no reason to use die() when encountering an error.

ps: Never make your error message say “I have a boo boo” ;)

Share this:
  1. 15 Responses to “The “do X or die()” pattern must die”

  2. Adding to the PS:

    If your native tongue is other than the one you live and program, don’t use ‘boo boo’ language to report errors or add random ‘echo’ statements to trace bugs. You never know who will be watching when demonstration time comes! :)

    By Nikolaos Dimopoulos on Jul 28, 2010

  3. I remember trying to use a reCAPTCHA library from inside a CMS – the library had a die in it for when it couldn’t contact their servers, meaning the CMS would stop dead and roll back all its transactions… unhandy.

    By Michael Maclean on Jul 28, 2010

  4. Google results so scary ? I mean.. look for official php.net documentation which is full of “die()” examples for mysql and mysqli functions.
    This is maybe be only for simplicity (to keep examples short), and for reason that Exceptions are hard to implement in purely procedural code. They are natural inhabitants of OO code.

    And so, only PDO has good examples of error handling, but it is no strange, if you will not catch Exceptions you will (by default) result in displaying database sensitive data on screen to everyone.

    So my advice to beginner developers is: learn PDO. Google for ‘php PDO mysql tutorial’ and you will find few good tutorials on the first page.
    Regards :)

    By e.s.t on Jul 29, 2010

  5. @e.s.t
    Why is it hard to implement exceptions in procedural code? I fail to see the difference with how it’s used in object-oriented code.

    By Hans-Eric Grönlund on Jul 29, 2010

  6. @Hans-Eric Grönlund
    Maybe I expressed it wrong. In simple scripts this doesn’t really matter and you can choose from a variety php exceptions. When your code is big things may go messy. And you cannot extend Exceptions (or manage them in a special matter) which in large projects take place very often (see ZF, Doctrine or Symfony).
    In PHP things are different as most of native functions return false or just trigger an error (or warning), while in languages like Python or Ruby everything throws an exception. So you can actually do:
    try:
    abs()
    except TypeError:
    print (‘I have a boo boo parameter’)

    By e.s.t on Jul 29, 2010

  7. I have also seen the use of die() in some PHP books, which is just lazy writing in my opinion. I agree that taking the try/catch approach to error handling is the way to go, and I would strongly recommend to new PHP programmers to learn about exceptions and extending the base Exception class in PHP.

    By john on Jul 29, 2010

  8. Amen brother. And that goes for you too exit()!

    Only time I use die() is quick and dirty debugging, and those are quickly removed once I figure out whatever I needed to know.

    By Carl on Jul 29, 2010

  9. “If your code dies, you won’t know the line. You won’t know the function, and not the file.”

    What about this?
    die(“Error in “.__LINE__.” from “.__FUNCTION__.” in .”__FILE__);

    Its only another method to do things in PHP. And thats wonderful. Think about it. ;-)

    By PHP-Beginner on Jul 30, 2010

  10. if (do_X_or_dir_pattern())
    {
    die();
    }

    :D

    By davide on Jul 30, 2010

  11. PHP-Beginner, If you really want to write more code to achieve the same result – feel free. However, if your code with that die() call was to fail in production, your error log would never show it and you would never know.

    By Jani Hartikainen on Jul 31, 2010

  12. Good error handling is one of the most important aspects of building web apps. The user experience is horribly degraded by users getting blank error pages or pages with with cryptic errors.

    Also, there’s no chance to log additional information, such as stack traces, and the contents of globals, so there’s no way to attempt to recreate and fix errors.

    By Chris Henry on Jul 31, 2010

  13. But they have their role as well. Like when creating cli scripts, where either parameters are missing or wrong parameters specified.

    By mhitza on Aug 3, 2010

  14. The die() function is just a way to end program execution. As the PHP Manual states, it is analogous to exit(). Exceptions do not inherently end program execution.

    In some cases, like programming command line utilities, you may want to even catch an Exception, and exit() with a return value to be interpreted by a calling script. So if you have used exit before, you probably have broken your “never use die()” rule.

    By Anonymous on Aug 15, 2010

  1. 2 Trackback(s)

  2. Aug 8, 2010: Savaitės skaitiniai #2 « Tyliu
  3. Aug 14, 2010: Exceptions and abstraction | CodeUtopia - The blog of Jani Hartikainen

Post a Comment

You can use some HTML (a, em, strong, etc.). If you want to post code, use <pre lang="PHP">code here</pre> (you can replace PHP with the language you are posting)