19 Exception Handling

Hiren Joshi

epgp books

 

 

 

Generally you believe that the program written by you is error free and will execute successfully. However, in few cases the program can terminate while it is executing. For example, if we have written a program which connects to a particular website and download the web pages. In normal condition, the program will execute as we expected but suppose the program runs on a computer which has not internet connection then the program will produce unexpected output. There can be similar situation, where the program open a file to read it, but the file is not exists. Such cases are known as exception. Exception result in abnormal execution and it may lead to abnormally terminate the program.

 

Exceptions are runtime errors. When writing the code, you should consider any unexpected runtime error. Exception handling allows the program to execute as there is no error in the code or it can terminate the program gracefully.

 

Types of error

 

There are 2 types of error.

 

1. Syntax error

2. Runtime error

 

Syntax errors occur when there is the syntax is not correct in the code. For exmplae, instead of echo statement, it is written as ehco.

 

<?php

$p = 1000;

$rate = 10;

$n = 2;

$si = ($p*$r*$n)/100;

ehco “Simple Interest for Principal $p, rate $rate for duration $n is : $si”;

?>

 

The output is:

 

( ! ) Parse error: syntax error, unexpected ‘”‘ in H:\wamp\www\PathshalaWAD\Exception Handling\1. types of error.php on line 6

 

Runtime errors are errors which occur during the execution of program. For example, in the program you want to display the value of array element which does not exists.

 

    <?php

$cities = array(‘Ahmedabad’,’Rajkot’,’Surat’,’Vadodara’);

$count = count($cities);

for($i=0;$i<=$count;$i++)

{

echo $cities[$i].”<br>”;

}

?>

The output is:

Ahmedabad

Rajkot

Surat

Vadodara

 

A program may have logical errors. Logical error is a error in which program execute without any error but the output is not as per expectation. For example, in following program as per simple interest formula

 

$si = ($p*$r*$n)/100 it is divided by 10. Hence though the program execute without any error but instead of correct simple interest 200 it displays 2000.

 

<?php

$p = 1000;

$r = 10;

$n = 2;

$si = ($p*$r*$n)/10;

echo “Simple Interest for Principal $p, interets rate $r for duration $n is : $si”;

?>

 

The output is:

 

Simple Interest for Principal 1000, interets rate 10 for duration 2 is : 2000

 

Exception Handling

 

Exception handling is used to handle unexpected error conditions. Exception handling is changed the normal flow of the code execution if a specified error (exceptional) occurs.

 

Exception can be thrown from your own exception and then write codes to handle it.

 

The syntax for creating a new exception is:

 

new Exception ($message [, $code] )

 

$message is a string. If $message is not string, it is converted to string.

 

$code is optional. In case $code is not supplied, it is taken as 0(Zero).

 

The syntax to throw statement is:

 

throw $exception

 

throw statement is used to throw an exception object. The throw statement can throw new or existing exception.

 

When an exception is occurred, then

  • The current code state is saved
  • The code execution will transfer to a predefined exception handler block.
  • Depending on the situation, the handle take action like terminate the script execution or continue executes the script from different location in the code.

 

Following code shows example of throw statement.

 

<?php

function simple($p,$r,$n)

{

if($p <= 0 || $r <= 0 ||$n <= 0)

{

throw new Exception(“Please enter valid values”);

}

$si = ($p*$r*$n)/100;

   echo “<br> Simple Interest is: $si”;

}

$p = 1000;

$r = 0;

$n = 2;

$ans = simple($p,$r,$n);

?>

 

 

Exception object has many methods which help to find out more about the exception.

 

Below table shows methods of exception object.

 

Method Description
getMessage( ) Returns the message set in the exception object
getCode( ) Returns the code set in the exception object
getFile( ) Returns the file in which the exception object was thrown
getLine( ) Returns the line in which the exception object was thrown
getTrace( )

 

 

Returns the array having a stack trace for the exception object.

A stacktrace is a list of functions or methods in reverse ordered

in which they were called when the exception was thrown.

getTraceAsString( ) Returns the string having a stack trace for the exception object
_toString( )

 

 

Allows to echo an Exception Object. It contains

information of exception object provided as all the above

method.

 

When an exception is thrown, it is required to catch it and handle it. In case it is not handles it, the program ends with a runtime error. Try-catch statement is used to catch the exceptions which are thrown.

 

Syntax for try-catch statement is shown below:

 

try

{

statement(s);

}

catch (ExceptionClass $exception)

{

     statement(s);

}

[ catch (ExceptionClass $exception)

{

statement(s);

} ]

 

 

In try-catch statement, try block contains the statements which may throw exceptions. In case, any exception does not trigger, the code will be executed as normal.

 

Throw statement trigger an exception. Each throw must have at least one catch block.

 

Catch block contains the statements to execute when an exception is thrown in the try block.

 

At the beginning of the catch block, you code the name of the class that defines the exception followed by a variable which allows you to access the exception object.

 

 

<?php

function simple($p,$r,$n)

{

if($p <= 0 || $r <= 0 ||$n <= 0)

{

throw new exception(“Please enter valid values”);

}

$si = ($p*$r*$n)/100;

echo “<br> Simple Interest is: $si”;

}

$p = 1000;

$r = 0;

$n = 2;

try

{

$ans = simple($p,$r,$n);

}

catch(Exception $e)

{

echo “Error: “.$e->getMessage();

}

?>

 

Then the output will be:

 

Error: Please enter valid values

 

When an exception is thrown, the code following the throw statement will not be executed and PHP try to find the catch block.

 

There must be at-least one catch block for handling exception triggered from try block.

 

Creating Custom Exception

 

The Exception class is the base class for all the exception. It can be inherited to create custom exception object. The custom exception class inherits the properties and methods from Exception class and it can be extended by adding custom functions to it.

 

Following code shows an example by creating custom exception.

 

<?php

//create custom exception class

class customException extends Exception

{

public function errorMessage()

{

$errormsg = “Error on line “.$this->getLine().’ in <br>File: ‘.$this->getFile(). ‘Error Message <b>’.$this-                   >getMessage().'</b><br>Please enter valid inputs’;

return $errormsg;

}

}

function simple($p,$r,$n)

{

if($p <= 0 || $r <= 0 ||$n <= 0)

{

throw new customException();

}

$si = ($p*$r*$n)/100;

echo “<br> Simple Interest is: $si”;

}

$p = 1000;

$r = 0;

$n = 2;

try

{

$ans = simple($p,$r,$n);

}

catch(Exception $e)

{

echo “Custome Exception <br>”.$e->errorMessage();

}

?>

 

    The output is:

 

Custome Exception

Error on line 16 in

File: H:\wamp\www\PathshalaWAD\Exception Handling\6. custome exception.phpError Message Please enter valid inputs

 

Multiple Exceptions

 

The Exception class represents the most general types of exception and its subclasses represent more specific types of errors.

 

In case you code multiple catch statements, you should code the most specific exception class first and end with the Exception class.

 

Multiple exception can be used for several if-else blocks or switch statement or to nest multiple exception. Following code shows two exception which shows different error message.

 

Following code shows an example of multiple exception.

 

 

<?php

//create custom exception class

class customException extends Exception

{

public function errorMessage()

{

$errormsg = “Error on line “.$this->getLine().’ in <br>File: ‘.$this->getFile(). ‘Error Message <b>’.$this-           >getMessage().'</b><br>Please enter valid inputs’; return $errormsg;

}

}

function simple($p,$r,$n)

{

if($p <= 0 AND $r <= 0 AND $n <= 0)

{

throw new customException();

}

if($p <= 0 )

{

throw new Exception(“Please enter valid principal”);

}

if ($r <= 0)

{

throw new Exception(“Please enter valid rate”);

}

if($n <= 0)

{

throw new Exception(“Please enter valid duration”);

}

$si = ($p*$r*$n)/100;

echo “<br> Simple Interest is: $si”;

}

$p = 1000;

$r = 0;

$n = 2;

try

{

$ans = simple($p,$r,$n);

}

catch(customException $e)

{

echo “Custome Exception <br>”.$e->errorMessage();

}

catch (Exception $e)

{

echo $e->getMessage();

}

?>

 

The output is:

 

Please enter valid rate

 

Re-throwing Exceptions

 

Sometimes, it is required to handle an exception differently than the standard way when an exception is thrown.

 

If necessary, you can code throw statement inside a catch block to re-throw the exception.

 

For example, A system should hide system errors from users as these errors are not meaningful to him. System errors are important for developer. At that time, exception can be re-thrown to a user with a user friendly message.

 

 

<?php

//create custom exception class

class customException extends Exception

{

public function errorMessage()

{

$errormsg   =   “<br>   Error   on   line   “.$this->getLine().’    in   <br>File:     ‘.$this-

>getFile().

“Error Message <b>”.$this->getMessage().”</b><br>Please enter valid inputs”; return $errormsg;

}

}

// inputs

$p = 1000;

$r = 0;

$n = 2;

// function

function simple($p,$r,$n)

{

$si = ($p*$r*$n)/100;

return $si;

}

try

{

try

{

if($p <= 0 )

{

throw new Exception(“Please enter valid principal”);

}

if ($r <= 0)

{

throw new Exception(“Please enter valid rate”);

}

if($n <= 0)

{

throw new Exception(“Please enter valid duration”);

}

if($p <= 0 || $r <= 0 || $n <= 0)

{

throw new customException();

}

}

catch(Exception $e)

{

echo “<br> Exception :”.$e->getMessage();

throw new customException();

}

}

catch (customException $e)

{

echo $e->errorMessage();

}

$ans = simple($p,$r,$n);

echo “<br> Simple Interest : $ans”;

?>

 

The output is:

 

Exception :Please enter valid rate

Error on line 47 in

 

File: H:\wamp\www\PathshalaWAD\Exception Handling\8. rethrow exception.phpError Message

Please enter valid inputs

Simple Interest : 0

 

Points to ponder for exception

  • Write the executable code in try block to help to catch potential exceptions
  • Each try or throw statement must have at least one corresponding catch block.
  • Multiple catch blocks can be used to catch various types of exceptions
  • Exception can be thrown or re-thrown in a catch block within a try block
  • The thumb rule is that if you are throwing something, you have to catch it.
you can view video on Exception Handling

References:

 

1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,

2. W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional, Apress

3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K. Glass:Beginning PHP5, Apache, and MySQL Web Development, Wrox,

4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media

5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove: Professional PHP, Wrox

6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible

7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach

8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications

9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams

10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide, Pearson Education

11. www.php.net

12. http://www.w3schools.com/

13. http://www.tutorialspoint.com/