Vault Tec   All about the Kinder™
I am the CEO/Co-founder of E29 Incorporated. I've been in the software industry for ten years now, have experience in about ten different computer languages, and once wrote a 60,000 line web application in three months without caffeine. I really wouldn't want to do that again.
Read more about me here, stalker.
 

Exceptions, ur doin it wrong

Ok, I’ve seen this crap come up like ten times in the past month. Usually from PHP “developers” unfortunately, even those with the ZCE badge of honor ( I expect better from you guys! ).

Exceptions are NOT for userland errors. Throwing an exception, especially in PHP, is very expensive.

This is another perfect example of PHP adopting a methodology from another language, and then not guiding their developers in the right direction.

This, is wrong:

if( !$user_email )
{
throw new Exception( "You have to fill out the email field" );
}

A good rule of thumb, if it couldn’t fit logically in a try/catch statement, then it’s not an exception. This is a good use for exceptions:


if( !$dbInstance )
{
// Something went wrong with the DB connection
try
{
$dbInstance = new dbObject();
}
catch( MyDBException $e )
{
print "Something broked: ".$e->getMessage();
}
}

7 Comments

  1. Chris Spurlock on 14.10.2008 at 18:36 (Reply)

    How do people consider not filling out the complete form an exception? Exceptions should only be used for semi-unpredictable errors caused by the application. I can very well predict someone is not going to fill in every field once in a while. Keyword was “someone”, and not the “application”.

  2. Calvin on 14.10.2008 at 19:24 (Reply)

    ur website needz syntacks highlighter.

    1. Adam Kinder on 14.10.2008 at 20:21 (Reply)

      srsly, I can’t stand when it strips out the friggin slashes

  3. TehBilly on 14.10.2008 at 20:02 (Reply)

    http://wordpress.org/extend/plugins/wp-syntax/ There’s a good syntax highlighter for ya. Sexy, easy, yay.

    Honestly, I’ve never found a need for exceptions. Does this make me fail?

    1. Adam Kinder on 14.10.2008 at 20:23 (Reply)

      Nein, I don’t use them in PHP. I use them a lot in Java though

      1. Chris Spurlock on 16.10.2008 at 12:57 (Reply)

        Aye, Java run-time exceptions FTW.

  4. Calvin on 14.10.2008 at 21:23 (Reply)

    I have yet to find any instance of them in our PB applications either.

Leave a comment