Bookmark and Share

PHP exception handling.

Posted: Sunday, August 23rd, 2009 at 11:09 amUpdated: Sunday, August 23rd, 2009 at 11:12 am

I normally post tutorials, how-tos or the likes. This post is a little bit different than the others. It’s more like a thought that I came across when I finally decided to use PHP’s exception handling.

Here’s the basic form of PHP’s exception handling.

try {
	// Do something
} catch (DataErrorException $e) {
	// Handle data error here
} catch (Exception $e) {
	// Handle general error here
}

The purpose of having the ability to have multiple catch blocks is so that it can be used to catch different classes of exceptions. Pretty standard, I think, as Java is also having similar form of try-catch clause.

However, from PHP manual :


PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which the variable is used.

Unlike C, C++, Java or other strongly typed languages, PHP is a loose typing (or weak typing) language. Therefore, it doesn’t require nor support explicit type definition in variable declaration. PHP will juggle a variable type depending on the context of the statement.

So what’s with the post, you may ask.

Well, in my opinion, PHP contradicts itself in the try-catch form because it requires you to declare a variable type for $e to be of some Exception class type. But before you yell at me saying that the class type in the catch clause is for PHP to match which exception to catch and not really for a variable type declaration, do consider the form is pretty much standard for type declaration in a strongly typed languages.

In the spirit of consistency, I think it would have been better if the PHP grammar for try-catch is in the following form so at least it’ll be consistent with the loose-type paradigm that PHP adhere to.

try {
	// Do something
} catch ($e) {
	// Handle error here
}

But that’s not the same

Again, before you jump me into saying that “what if I want to catch only DataErrorExepction as in your example above”, consider that PHP has a built-in get_class() function. I think the function is self explanatory. So now getting back to your question, IMHO PHP should have handled the exception as follows:

try {
	// Do something
} catch ($e) {
	switch (get_class($e)) {
		case 'DataErrorException':
			// Handle data error here
			break;
		default:
			throw $e;
	}
}

The above code, in theory, I think is congruent with the way PHP’s syntax of exception handling. The only difference (other than the fact that it won’t run in PHP) is that it is completely loose-type syntax, and thus, I think, is what PHP developers should have implemented if they want to be consistent with loose-type paradigm of PHP.

Leave a Reply