PHP Exceptions and Namespaces

I’m way too late to the PHP namespace conversation. Initially I just didn’t see the benefit of namespaces, but now I’ve seen the light. ¬†The other issue was the production environment at work¬†didn’t support ¬†namespaces – I own that problem too. ¬†Basically for way too long it was a big fail fest.

But now angel choirs are singing and I’ve seen the light. ¬†I preface this post with these details in case you already know what I’m about to write about.

I just spent 20 minutes trying to figure out why the same pattern of code worked in one place but not another. ¬†I’m trying to validate date strings in form submissions and had some code like this:

function validateDate()
{
	try
	{
		$dt = new \DateTime( $fieldValue );
	}
	catch( Exception $e )
	{
		return false;
	}

	return true;
}

The error I was seeing was an uncaught exception for an invalid date format. ¬†That’s exactly what I was trying to prevent!

It took me way too long to realize that I needed to namespace the Exception class.

The solution is either to

use Exception;

at the top of my class file or to rewrite the function.

function validateDate()
{
	try
	{
		$dt = new \DateTime( $fieldValue );
	}
	catch( \Exception $e )
	{
		return false;
	}

	return true;
}

 

TLDR:¬†Make sure you namespace the class names in your catch blocks otherwise it’s ignored and the exception is not caught.