I have been using try..catch blocks in my PHP code, but I'm not sure if I've been using them correctly.
For example, some of my code looks like:
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
$tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (Exception $e) {
return $e;
}
So I'm grouping multiple database operations in the same try/catch block because if any exception occurs in any of the transaction, I will be able to handle it.
I'm doing it that way because I think that it's more readable and efficient than:
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
} catch (Exception $e) {
return $e;
}
try {
$tableBresults = $dbHandler->doSomethingWithTableB();
} catch (Exception $e) {
return $e;
}
Although, I'm not sure if what I'm doing is a good practice or just a lazy way to catch exceptions.
My assumption is that only if an exception requires special handling, it should have its own try/catch block, otherwise grouping them in the same try/catch should be ok.
So my question(s) are:
Is there any advantage of using try/catch blocks per database transaction? or can I still group multiple database transactions in the same try/catch block with no problem at all?
Is it ok to nest try/catch blocks?
Thanks!
EDIT
The return statement was primarily for demonstration purposes only, but I'm also using returns in catch()
because I'm making an AJAX request to that method, and Javascript is expecting a JSON object, then if an exception occurs I return an empty JSON encoded array. I just thought that It wouldn't add any value to put specific code in my example.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…