Welcome to my series on every PHP keyword and its usage. Today’s items: try, catch and finally.

These keywords help your code to gracefully handle exceptions that would otherwise end its execution with an ugly error message.

The try block includes the code that might throw an exception, while the catch block(s) handle any exceptions thrown in the try block.

Simple example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
try
{
	$time = new DateTime($_GET["date"]);
}
catch(Exception $e)
{
	echo "Could not parse date format, please try again";
	exit;
}

Multiple catch blocks

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
try
{
	$twitter->getTweets();
}
catch(CommunicationException $e)
{
	echo "Could not connect to Twitter, please try again later";
	exit;
}
catch(AuthenticationException $e)
{
	echo "You are not signed in, please sign in and try again";
	exit;
}

Combined catch blocks

1
2
3
4
5
6
7
8
9
<?php
try
{
	$twitter->getTweets();
}
catch(CommunicationException | AuthenticationException $e)
{
	echo "Something went wrong, please try again later";
}

finally

The finally block contains code that will be executed whether or not an exception is thrown. It will be executed even if a catch statement closes the current scope.

The finally block is typically used to close any open connections or file pointers that would otherwise be left dangling, and to tidy up any other loose ends.

PHP does not require you to use a catch block if you have a finally block.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php
$twitter = new Twitter();
$twitter->connect();

try
{
	$twitter->sendTweet("There is no 'I' in 'me'.");
}
catch(ConnectionException $e)
{
	echo "Could not send tweet, please try again later";
	exit;
}
finally
{
	$twitter->disconnect();
}