Error Handling in PHP

Error handling is the process of catching errors from the program and then taking appropriate action. Before proceeding for error handling you should get to know how many types of errors occurred in PHP.

Notices: These are non-critical errors that occurred while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although, as you will see, you can change this default behavior.

Warnings: These are more serious errors – for example, attempting to use a file (using include() method) which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

Fatal Errors: These are critical errors – for example, creating an object of a non-existent class, or calling a function which doesn’t exist in your program. These errors cause the immediate termination of the script, and PHP‟s default behavior is to display them to the user when they take place.

It‘s very simple in PHP to handle errors.

Using die() function

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

Example 1:




die(“File not found”);




$file = fopen(“/docs/resume.txt”,”r”);



Example 2:


$a = 0;

$b = 200;

$result = $b/$a;

echo “RESULT: “. $result;


Output: Warning: Division by zero in … on line 4

Example 3:


echo “Hi lets learn PHP”

echo “<br/>This is another line”;


Output: Parse error: syntax error, unexpected ‘echo’ (T_ECHO), expecting ‘,’ or ‘;’ in … on line 3

Leave a Reply

Your email address will not be published.

Enjoy the tutorial? Please spread the word :)

Follow by Email