Exceptions, ur doin it wrong
By Adam Kinder on Oct 14, 2008 in Programming | comments(7)
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();
}
}
