PHP try-catch

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 occurred while executing PHP scripts. Such exceptions are caught with PHP catch block.

php_try_Catch

For each try block in a PHP program, there should be minimum one catch block. We can have multiple catch blocks for a try block, to handle various classes of PHP exceptions.

PHP try-throw-catch Syntax

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

Simple PHP Example for try-catch

Let us have an simple PHP try-catch example by using 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, try block checks the length of the PHP global array variable $_GET to print its element by iterating over PHP foreach block.

If the length of $_GET array is 0, then, an exception will be thrown. The loop and throw statements are handled with if and else part of try block in the above PHP program.

PHP try with Multiple catch

As we have specified at the beginning, multiple catch blocks for single PHP try block is used to handled classified exceptions. For example, PHP library provides separate exception class as LogicException, RunTimeException and etc by inheriting parent Exception class.

The following PHP program contains several conditional blocks throwing different kind 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 co-ordinates, we should evaluate all parameters before pass into this function.

On performing PHP validation, if anything wrong with the datatype, then InvalidArgumentException will be thrown. In case, if the parameter array is empty, then Exception class instance is used to throw. These two classification of exceptions are handled with two independent catch blocks provided for a single try block used in this example.

Nested try-catch in PHP

We can create nested PHP blocks to handled subsequent exceptions each occurred by the cause of previous one. For example, if we upload a file, we need to check about its existence. If no such file is exist, then will PHP caught file not found exception and there by cause unable to upload file error.

In such situation, we can use nested try-catch blocks to display error message regarding all exceptions 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 Exception class’s previous error instance, we can capture nested exception. And, this program will return the following output.

unable to upload file
Previous Error: file not found

Note:

  • Apart from PHP Exception class and its subclasses, we can also created some custom classes to handle exception to catch uncaught exceptions.
  • Not one custom classes, but also we can set an user defined function as an exception handler function by using set_exception_handler() PHP function.
  • With PHP version 5.5 and above, we can use finally blocks to handle exception. This blocks will be executed any way if the exception is thrown or not.

Download PHP TRY CATCH Source Code

This PHP code tutorial was published on September 13, 2013.

↑ Back to Top