Jiew Meng
Jiew Meng

Reputation: 88187

try catch does not catch exception?

I have code like below

try {
  $user = $query->getSingleResult();
} catch (Doctrine\ORM\NoResultException $e) {
  return null;
} catch (Exception $e) {
  return null;
}

getSingleResult() will throw NoResultException if no rows are found. and it seems I am still getting the exception ... the catch does not seem to work. why is that?

Upvotes: 13

Views: 9564

Answers (2)

Gayan Hewa
Gayan Hewa

Reputation: 2397

Its also possible to add a

 use Exception;

On the top of the class and it will resolve the Exception class name used in the try/catch block.

Upvotes: 3

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

If your code is namespaced, try using:

catch (\Doctrine\ORM\NoResultException $e)

Note the backslash in front of the Doctrine namespace.

The reason you need to do this is because PHP's namespaces are relative, instead of absolute.

If your code is namespaced to My\Namespace, and you try to catch Doctrine\ORM\NoResultException, in reality it tries to catch My\Namespace\Doctrine\ORM\NoResultException.

By prefixing the namespace with a \ you make it absolute (similar to unix pathnames)

Upvotes: 34

Related Questions