Error Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences.

Using die() function +

While wirting your PHP program you should check all possible error condition before going ahead and take appropriate action when required.

Try following example without having /tmp/test.xt file and with this file.

<?php
if(!file_exists("/tmp/test.txt"))
 {
 die("File not found");
 }
else
 {
 $file=fopen("/tmp/test.txt","r");
 print "Opend file sucessfully";
 }
 // Test of the code here.
?>

This way you can write an efficient code. Using abive technique you can stop your program whenever it errors out and display more meaningful and user friendly meassage.

Defining Custom Error Handling Function +

You can write your own function to handling any error. PHP provides you a framwork to define error handling function.

This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):

Syntax:

error_function(error_level,error_message, error_file,error_line,error_context);




All the above error level can be set using following PHP built-in library function where level can be any of the value defined in above table.

int error_reporting ( [int $level] )

Following is the way you can create one error handling function:

<?php
function handleError($errno, $errstr,$error_file,$error_line)
{ 
 echo "Error: [$errno] $errstr - $error_file:$error_line";
 echo "
"; echo "Terminating PHP Script"; die(); } ?>

Once you define your custom error handler you need to set it using PHP built-in library set_error_handler function. Now lets examine our example by calling a function which does not exist.

<?php
error_reporting( E_ERROR );
function handleError($errno, $errstr,$error_file,$error_line)
{
 echo "Error: [$errno] $errstr - $error_file:$error_line";
 echo "
"; echo "Terminating PHP Script"; die(); } //set error handler set_error_handler("handleError"); //trigger error myFunction(); ?>

Exceptions Handling +

PHP 5 has an exception model similar to that of other programming languages. Exceptions are important and provides a better control over error handling.

Lets explain thre new keyword related to exceptions.

  • Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".
  • Throw - This is how you trigger an exception. Each "throw" must have at least one "catch".
  • Catch - - A "catch" block retrieves an exception and creates an object containing the exception information.
  • When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ...

An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block.

Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions.

Exceptions can be thrown (or re-thrown) within a catch block.

Example:

Following is the piece of code, copy and paste this code into a file and verify the result.

<?php
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

In the above example $e->getMessage function is uded to get error message. There are following functions which can be used from Exception class.

  • getMessage()- message of exception
  • getCode() - code of exception
  • getFile() - source filename
  • getLine() - source line
  • getTrace() - n array of the backtrace()
  • getTraceAsString() - formated string of trace

Creating Custom Exception Handler:

You can define your own custome excpetion handler. Use following function to set a user-defined exception handler function.

string set_exception_handler ( callback $exception_handler )

Here exception_handler is the name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler().

Example:

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');

echo "Not Executed\n";
?>

PHP Exception Handling

PHP Error and Logging Functions

PHP Bugs Debugging +

To make error messages display in the browser, set the display_errors configuration directive to On. To send errors to the web server error log, set log_errors to On. You can set them both to On if you want error messages in both places.

PHP defines some constants you can use to set the value of error_reporting such that only errors of certain types get reported: E_ALL (for all errors except strict notices), E_PARSE (parse errors), E_ERROR (fatal errors), E_WARNING (warnings), E_NOTICE (notices), and E_STRICT (strict notices).