PHP try-catch

by Vincy. Last modified on July 9th, 2022.

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.

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 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.

PHP try with Multiple catch

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.

Nested try-catch in PHP

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:

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

Download PHP TRY CATCH Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page