Some exceptions in PHP don't get caught. Here's why.

What happend is this: I'm currently hacking away on my diploma thesis, involving some coding in PHP. No problem so far. In doing so, I'm using many features new in PHP 5.3, such as namespaces and some other niceties, which are of no concern for us today.

Namespaces do have a few weird side effects, one of which I discovered in the following story: Trying to implement some exception-catching code, I wrote the following lines:

try {
    $this->getNestedKey($name, $data);
}
catch (Exception $e) {
    return false;
}

There's nothing wrong with that code, really. Almost nothing. In fact, only one thing is weird: It never catches an exception, and I'm wondering why exactly that could be. The exception just got thrown further up the call stack, finally geting caught in the outermost error handler.

Now I have to apologize, because what I didn't tell you is this: The above code sits in a namespced class. So, when an exception is thrown, PHP goes along the catch() blocks to look for a match. Passing our catch(Exception $e), it (rightfully) thinks that this block wants to catch an Exception class that's defined within that namespace - which it of course is not.

So the correct way to write the above code snippet would be (with only one byte difference):

try {
    $this->getNestedKey($name, $data);
}
catch (\Exception $e) {
    return false;
}

As I said in the beginning, a statically typed language would probably have caught this slip during compile time. But for now, I have to live with a language that sometimes gives you absolutely no clue as to what's going wrong.