Catching multiple PHP exceptions

I had previously discussed using try / catch / finally and a fine reader pointed out that I didn’t mention catching multiple exceptions. He’s right, I dropped the ball and decided to dedicate today’s post to catching multiple exceptions.

To catch multiple exceptions you will need to be using code that will throw different types of exceptions. Most of the PHP extensions out there will throw their own custom exception that extends the Exception class. One of the most notable exception in my opinion is the PDOException. Let’s see how we can catch it alongside a standard Exception:

try
{
	$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password'

	throw new Exception('such broken'
}
catch (PDOException $e)
{
	echo 'There was an error connecting to the database'
}
catch (Exception $e)
{
	echo 'There was some other error'
}

With this example, unless you have a database named “database” and your username and password are named as such, will throw a PDOException that will be caught by the first catch. If you were to set up the PDO object with your own credentials it would clear up the PDOException and then the thrown Exception would be thrown and caught by the second catch. To the best of my knowledge, there are no limits to how many catch statements you can have with your try.

To take this a step further, we can introduce finally into the mix. finally is always executed afterwards regardless if an exception is thrown:

try
{
	$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password'

	throw new Exception('such broken'
}
catch (PDOException $e)
{
	echo 'There was an error connecting to the database'
}
catch (Exception $e)
{
	echo 'There was some other error'
}
finally
{
	echo 'We made it!'
}

The ability to catch each type of exception independently allows you to react different ways based on what’s throwing the error. Obviously a PDOException while trying to connect could be considered a fatal error while other errors may be less critical and you can code accordingly.

Something not touched on is the fact that you can have your own exception types that could also be caught in the same way. I think we’ll save that for next week though 🙂

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.