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?
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.
When code reports an error, an exception cannot be caught if the thread has not yet entered a try-catch block. For example, syntaxError, because the syntax exception is reported in the syntax checking phase, the thread execution has not entered the try-catch code block, naturally cannot catch the exception.
The try block includes the code that might generate an exception. The catch block includes the code that is executed when there occurs an exception inside the try block.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With