Beginner PHP Programmer Mistakes Part Two: Going Nutty with Exceptions
You’re a beginner PHP programmer, and your server has just been upgraded to PHP 5. Yay! Time to rewrite that error handling code to include exceptions! One mistake that beginner PHP programmers make is that they go crazy with exceptions. They might turn the below code:
function checkUsername ($username)
{
if (!is_string ($username))
{
die ('The username is invalid');
/* Also acceptable are:
* trigger_error (<something>);
* ^-- If you the proper error handling
* setup for site visitors.
*
* return <something>;
* ^-- Provided that the caller saves
* the return value and that the
* value is checked.*/
}
else
{
return true;
}
}
oldCheckUsername ($username);
into:
class OMGYourUsernameIsNotValidException extends
Exception {}
function checkUsername ($username)
{
if (!is_string ($username))
{
throw new OMGYourUsernameIsNotValidException
('Username = fail');
}
else
{
return true;
}
}
try
{
checkUsername ($username);
}
catch (OMGYourUsernameIsNotValidException $e)
{
echo $e->getMessage ();
}
Exceptions are best used for things like a database connection failing. They aren’t really for simple things like form validation.
Uncaught PHP exceptions are considered E_FATAL errors, and I consider that a good measurement of whether or not you need exceptions. While you might want to terminate script execution in the case of improperly filled in forms, you wouldn’t want to use that error level for form validation.
A failed database connection seems to fit well into E_FATAL, and by that logic, it’s okay to use exceptions for it.
Disagree? Know a better way to handle errors in PHP? Tell me in the comments.
Posted in PHP, Uncategorized | View Comments