Menu

PHP TUTORIALS - PHP Error Handling

PHP Error Handling

ADVERTISEMENTS

Using die() function:


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

ADVERTISEMENTS

Defining Custom Error Handling Function:

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

ADVERTISEMENTS

Parameter Description
error_level Required - Specifies the error report level for the user-defined error. Must be a value number.
error_message Required - Specifies the error message for the user-defined error
error_file Optional - Specifies the filename in which the error occurred
error_line Optional - Specifies the line number in which the error occurred
error_context Optional - Specifies an array containing every variable and their values in use when the error occurred


int error_reporting ( [int $level] )


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


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

//trigger error
myFunction();
?>

Exceptions Handling:


<?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';
?>


string set_exception_handler ( callback $exception_handler )


<?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";
?>