Yes, your approach is correct. Using Try...catch
may lead into cleaner and more readable code in some cases but your overall approach is fine.
If your code fragment is from a function that handles DB queries and not much else, I'd probably switch the approach around:
// Begin Transaction
$this->db->beginTransaction();
// Fire Queries
if(!$query_one->execute()){
$this->db->rollback();
// other clean-up goes here
return;
}
if(!$query_two->execute()){
$this->db->rollback();
// other clean-up goes here
return;
}
$this->db->commit();
Of course, if you require lots of clean-up to be done before you can return
, then your original approach is better. Especially in these cases I'd look into using PDO::ERRMODE_EXCEPTION. This has some additional benefits, like exceptions automatically rolling back the transaction unless they are caught.