PHP try-catch is implemented with try and catch blocks, as usual. And, try block contains code with the feature of PHP exception handling by throwing exceptions that occurred while executing PHP scripts. Such exceptions are caught with PHP catch block.
For each try block in a PHP program, there should be a minimum of one catch block. We can have multiple catch blocks for a try block, to handle various classes of PHP exceptions.
The following code block shows the usage of try and catch in a PHP program.
<?php
try {
// any code throws exception
} catch (Exception $e) {
// code to print caught exception
}
?>
Let us have a simple PHP try-catch example by using the above syntax.
<?php
try {
$get_vars = count($_GET);
if ($get_vars != 0) {
foreach ($_GET as $key => $value) {
echo $key . " = " . $value . "<br/>";
}
} else {
throw new Exception("PHP GET global array is empty");
}
} catch (Exception $e) {
echo $e->getMessage();
}
?>
In the above example, the try block checks the length of the PHP global array variable $_GET to print its element by iterating over the PHP foreach block.
If the length of the $_GET array is 0, then, an exception will be thrown. The loop and throw statements are handled with if and else part of the try block in the above PHP program.
As we have specified at the beginning, multiple catch blocks for a single PHP try block are used to handle classified exceptions. For example, the PHP library provides separate exception classes as LogicException, RunTimeException and etc by inheriting the parent Exception class.
The following PHP program contains several conditional blocks throwing different kinds of PHP exceptions accordingly. For example,
<?php
$time_param1 = array(
1,
2,
3,
"four",
5,
6
);
try {
$timestamp1 = get_timestamp($time_param1);
print "PHP time stamp - " . $timestamp1 . "<br/>";
} catch (Exception $e) {
echo $e->getMessage();
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
function get_timestamp($time_param)
{
$time_param_length = count($time_param);
if ($time_param_length != 0) {
for ($i = 0; $i < $time_param_length; $i ++) {
if (! is_numeric($time_param[$i])) {
throw new InvalidArgumentException("parameter $i should be numeric, " . gettype($time_param[$i]) . " is given");
}
}
} else {
throw new Exception("no argument is passed for calculating timestmap");
}
$timestamp = mktime($time_param[0], $time_param[1], $time_param[2], $time_param[3], $time_param[4], $time_param[5]);
return $timestamp;
}
?>
In this example, we are calculating timestamp value using PHP mktime() with the given array of parameters. Since mktime() accepts numeric values as date coordinates, we should evaluate all parameters before they pass into this function.
On performing PHP validation, if anything is wrong with the datatype, then InvalidArgumentException will be thrown. In case, if the parameter array is empty, then the Exception class instance is used to throw.
These two classifications of exceptions are handled with two independent catch blocks provided for a single try block used in this example.
We can create nested PHP blocks to handle subsequent exceptions each occurring by the cause of the previous one. For example, if we upload a file, we need to check for its existence. If no such file exists, then will PHP caught the file not found an exception and thereby cause unable to upload file error.
In such a situation, we can use nested try-catch blocks to display an error message regarding all exceptions that occurred. For example,
<?php
try {
upload_file("testfile.php");
} catch (Exception $e) {
echo $e->getMessage() . "<br/>";
while ($e = $e->getPrevious()) {
echo 'Previous Error: ' . $e->getMessage() . "<br/>";
}
}
function upload_file($filename)
{
try {
if (file_exists($filename)) {
// code for file uploading
} else {
throw new Exception('file not found');
}
} catch (Exception $e) {
throw new Exception('unable to upload file', 0, $e);
}
}
?>
By passing the Exception class’s previous error instance, we can capture nested exceptions. And, this program will return the following output.
unable to upload file
Previous Error: file not found
Note:
Download PHP TRY CATCH Source Code