13

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?

0

2 Answers 2

34

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)

Sign up to request clarification or add additional context in comments.

3 Comments

This is most likely because the user is using Doctrine 2 which is namespaced.
Using Doctrine 2 does not force you to namespace your own code though. In a case where you haven't specified a namespace for your code, the namespace is always assumed to be at root, in which case you wouldn't need the initial \
You can as well just do a catch of NoResultException and add a use Doctrine\ORM\NoResultException; in your file header.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.