Jump to content

Catching multiple exceptions


Go to solution Solved by requinix,

Recommended Posts

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;
}

 

Link to comment
https://forums.phpfreaks.com/topic/303428-catching-multiple-exceptions/
Share on other sites

  • Solution

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
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.