Thursday, 30 November 2017

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 a 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 a 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 the 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 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 handled subsequent exceptions each occurred by the cause of 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 file not found an exception and there by cause unable to upload file error.
In such situation, we can use nested try-catch blocks to display an 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 create some custom classes to handle exception to catch uncaught exceptions.
  • Not one custom classes, but also we can set a 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 the exception. This blocks will be executed anyway if the exception is thrown or not.

0 comments:

Post a Comment