How to Try Catch in symfony

Exception Type is - \Doctrine\ORM\EntityNotFoundException Don`t forget starting "\" Example -

 try {
        $entityManager = $this->getEntityManager();
        $entityManager->remove($entity);
        $entityManager->flush(); // save to the database
    } catch (\Doctrine\ORM\EntityNotFoundException $ex) {
        echo "Exception Found - " . $ex->getMessage() . "<br/>";
    }

the Exception thrown by Doctrine is called Doctrine\ORM\EntityNotFoundException and you are catching EntityNotFoundException.

Thats a difference, the namespace matters.

to debug this, catch Exception instead and observe the type of the actual exception. then replace it.


if you're trying to catch any exception, you should use a backslash before "Exception".

E.g.:

try{
    //do stuff here
}
catch(\Exception $e){
    error_log($e->getMessage());
}

If you don't use a backslash, the exception won't be caught. This is due to how namespaces are used in PHP / Symfony.

Tags:

Php

Symfony