Error and Exception Handling in PHP

Handling errors and exceptions lay at the core of robust PHP programming. You should handling all the possible errors and exceptions before your website go into deployment. There are multiple ways of handling errors and exceptions in PHP. This article throws light on two of the most commonly used methods for error and exception handling.

The die() function

The simplest way of handling errors in PHP is by using die() function. Enclose the piece of code capable of throwing an error into an if statement, and if the code within the if statement returns false, display an appropriate message to the user and close the PHP script via die() function. Have a look at the first example.


          Program is exiting.";
}
else
{
    echo "your file exists and is being opened.";
}
?>

Download the code
Run the code

In the above code, it is being checked if the file “somefile.txt” exists. If it doesnt, exist the server responds with an error message and program is closed.

Try, Throw and Catch

PHP 5 has introduced a new error handling mechanism. The statements where there is a possibility of error are enclosed in a try block and if exception occurs within that block, the control shifts to the corresponding catch block where exception can be handled in an appropriate way. Have a look at the following example.

";
    throw new Exception($exc);
}
$result = $number1/$number2;

echo $result;
}
catch(Exception $exc)
{
    echo "Exception occured: ".$exc->getMessage();  
}
echo "Program keeps on executing.";
?>

Download the code
Run the code

In the above example, a number is being divided by the other. An if statement has been used to check whether the denominator is zero or not. If the denominator is zero it throws an exception using throw keyword. To throw an exception, throw keyword is used followed by the Exception object which takes error message as parameter to the constructor. When the exception occurs, control shifts to the catch block. To get the message of the exception, the getMessage() function is called on the exception object passed to the catch block. PHP script continues its execution once an exception is handled by catch block.

<<< Math Functions in PHPReading XML data in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .