NotionCommotion Posted March 11, 2017 Share Posted March 11, 2017 Do I need to use two catch blocks, or is there a way to do it all in one? Thanks class BarException extends Exception {} public function foo() { try { $this->pdo->beginTransaction(); $this->doQuery(); $rsp=$this->doMethodWhichThrowsBarExtention(); $this->pdo->commit(); } catch(PDOException $e){ $this->pdo->rollBack(); $rsp=$e->getMessage(); } catch(BarException $e){ $this->pdo->rollBack(); $rsp=$e->getMessage(); } return $rsp; } Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted March 12, 2017 Solution Share Posted March 12, 2017 Only if you have PHP 7.1. Since backtrace information is decided at instantiation and not when thrown (unlike other languages), you could do the less glamorous } catch (Exception $e) { if ($e instanceof PDOException || $e instanceof BarException) { $this->pdo->rollBack(); $rsp = $e->getMessage(); } else { throw $e; } }but for only two lines of code it's not worth the added complexity. That said, you should rollback the transaction for every exception, so I suggest changing your code regardless. Using a finally means you can skip the $rsp variable too. $e = null; try { $this->pdo->beginTransaction(); $this->doQuery(); return $this->doMethodWhichThrowsBarException(); } catch (PDOException $e) { return $e->getMessage(); } catch (BarException $e) { return $e->getMessage(); } finally { if ($e || !$this->pdo->commit()) { $this->pdo->rollBack(); } } Demonstration 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.