php – What's the purpose of immediately rethrowing all Exceptions?-ThrowExceptions

Exception or error:

The documentation for Doctrine ORM says:

Note that when catching Exception you should generally re-throw the exception.

Why would you do that? What’s the rationale for it? Why not not use a try/catch block? Wouldn’t this:

try {
  /** @var EntityManager $em */
  $em->persist($user);
  $em->flush();
} catch (EntityException $e){
  throw  $e;
} catch (\Exception $e){
  throw  $e;
}

be the same as this?

/** @var EntityManager $em */
$em->persist($user);
$em->flush();

What’s the purpose of immediately rethrowing all Exceptions?

How to solve:

Your two examples are functionally equivalent, but that’s not what the quoted phrase refers to.

The quote you mention comes from the chapter on Transactions and Concurrency, specifically to explicitly demarcated transactions.

The quote refers to this kind of code:

$em->getConnection()->beginTransaction(); // suspend auto-commit
try {
    //... do some work
    $user = new User;
    $user->setName('George');
    $em->persist($user);
    $em->flush();
    $em->getConnection()->commit();
} catch (Exception $e) {
    $em->getConnection()->rollBack();
    throw $e;
}

In this case, the transaction is demarcated first by the beginTransaction() and the commit() calls.

If you do not use a catch block for this, there is no way for you to issue a rollBack(), and you would leave the transaction open. Yes, it may rollback automatically when the connection closes, but it’s better if you do it explicitly.

And the re-throwing the exception is advisable so you can let consumers know that something went wrong with the transaction, and do proper error handling. You could also throw a different kind of exception, or do a different kind of error handling.

Leave a Reply

Your email address will not be published. Required fields are marked *