How to use try/catch statements in PHP. Oh, and finally too!

I do a lot of coding in Python and one thing that I really love is the mindset of asking for forgiveness instead of permission. What’s this mean? It means that instead of sanity checking every little thing, just handling the exceptions that are thrown instead. In PHP this can be accomplished by using try/catch blocks:

try
{
	if (true)
	{
		throw new Exception('True? but we wanted False?!'
	}
}
catch (Exception $e)
{
	// Handles the exception
	echo 'Error: ' . $e->getMesssage
}

A pretty primitive example but that’s the gist of it, instead of writing code with nested if statements trying to control the flow, just wrap it all in a try/catch and the control structure will immediately be halted when you encounter an Exception (which you can throw yourself).

Unfortunately, PHP has it’s own error handling and Exceptions are not always thrown (quite the shortcoming in my opinion) but you can always override the default error handler and have it throw exceptions instead, which is something I’ve discussed in the past.

If you’ve joined me in the revolution of running the most recent version of PHP (5.5+ as of this writing) then you have access to the finally block as well. finally is code that will always be executed regardless if an exception is thrown. Please keep in mind that this only works if there is another try/catch block handling the code. That being said, this won’t work as you may expect:

try
{
	throw new Exception('Error!!'
}
catch (Exception $e)
{
	throw new Exception($e->getMessage());
}
finally
{
	echo 'I still ran!'
}

echo 'I did not run!'

Because the Exception being thrown inside the catch is not being caught, it raises a PHP fatal error. Now in this example, the finally will be executed:

try
{
	try
	{
		throw new Exception('Error!!'
	}
	catch (Exception $e)
	{
		throw new Exception($e->getMessage());
	}
	finally
	{
		echo 'I still ran!'
	}

	echo 'I did not run!'
}
catch (Exception $e)
{
	exit($e->getMessage());
}

Keep in mind this is just for demonstration purposes, a real world example would be in situations where you have some nested logic (possibly spanning multiple files and/or classes) that is catching and throwing errors, but you still want to execute pieces of code regardless.

Asking for forgiveness instead of permission generally keeps your code flatter and closer to the left margin which helps readability and simplifies the control structure. Another lesson learned here is that coding in other languages can help expose you to concepts that can be applied in your language of choice, no reason to limit yourself.!

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.