Techniques behind PHP Error Handling for Developer

In Software Designing “Zero Defects” is a Challenge. To achieve “Zero Defects” we depends upon many factors. Starting from “Developers Team” to “Quality Assurance” all are equally responsible for an error in production. To reduce error the primary role a developer’s play. I believe in the matter of Error or Exception handling a Experienced developer do better than a fresher. This is the cause we are hunting experience professionals. During an application development Coding Can any developer do but quality Coding is rare. To write an error free logic we required to understood “How Compiler works?” and what are the ways to handle exceptions. In this session let us share PHP Error Handling technique for Developer.

Practice to PHP Error Handling using Try Catch block

While implementing a logic do the Complex part (Which has more Chance for Exception) in-side Try .. Catch block. Try Catch block has 3 units Try, Catch and Finally. Each try block must at-least required one catch block. More than one catch blocks can be used to catch different classes of exceptions.

Let us assume you are going to insert a record to the database. In this case after created the SQL query dynamically, while executing that query do that inside the try block. During run-time if connection will break with Server during database interaction the execution will jump to Catch block. In Catch block you can know the Error & handle the Exception. Finally block execute at any case. If there is a error in try block then after Catch block finally block executes. Similarly if try block executes successfully then also Finally block executes. It is a best place for Close Database Connection.

Example of Try .. Catch

try {
throw new Exception('error');
catch(Exception $e) {
echo "There is an Error.";
throw $e;
finally {
// Code in Finally block Overrides the exception
return "\nException erased";

Some Errors occurs in run-time for those errors Try Catch is the best approach to deal. Let’s talk an another example. While Sending mail execute the Send() method in-side Try Catch block. In run-time in-case the SMTP Server is down. System will show the real error message “Mail Server is Down. Please try later”.

Use PHP die() method

Die() is a simple and effective PHP Error Handling method. When ever there is a possibility of an error use die() method. Generally die() method is useful for Conditional Checking. For an example if you are going to upload a file here while you are checking “is file exists?” using if(!file_exists("/tmp/logo.png")) use die() method to handle possible errors. Look at the example below.

if(!file_exists("/tmp/logo.png")) {
die("File is not exists Physically.");
} else {
$file = fopen("/tmp/logo.png","r");
print "Able to Open the File Successfully.";

In the above example before Opening the file I am checking is there any file exists to open. If there is no such files using die() method with message “File is not exists Physically.”. Die() method handles error as well as Clears memory whole. Kills unwanted process and helps to improve performance.

Create Custom Error Handler

Using PHP it is very easy to Create Custom Error handlers. The Syntax is as below.

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

While Creating a Custom Error function keep remember that the first two parameters are mandatory. The rest 3 (error_file, error_line and error_context) are optional. Error_level must be a value in number. Refer the below table to know more about the error_level values.

Value Constants Description
1 .E_ERROR Error level with value 1 indicates run-time Fatal errors. Execution of the script is halted.
2 E_WARNING Error level with value 2 indicated run-time Non-fatal errors. Compare to Error level 1 here execution of the script is not halted.
4 E_PARSE Error level with value 4 indicates Compile-time parse errors.
8 E_NOTICE Value 8 is for run-time notices. During execution the script found something that might be an error, but could also happen when running a script normally.
16 E_CORE_ERROR Error level with value 16 indicates Fatal errors. Fatal Errors generally occur during PHP initial start-up.
32 E_CORE_WARNING The error level value 32 speaks non-fatal run-time errors. This also occurs during PHP initial start-up.
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error().
512 E_USER_WARNING Error level with value 512 indicates Non-fatal user generated warning. It is similar to E_WARNING set by the developer using the PHP trigger_error() function.
1024 E_USER_NOTICE The error code with 1024 value speaks user-generated notice. This is like an E_NOTICE set by the developer using the PHP function trigger_error().
4096 E_RECOVERABLE_ERROR This error level says Catchable fatal error. It is like an E_ERROR but can be caught by a user defined error handlers.
8191 E_ALL The error level value 8191 indicates all errors and warnings.

All the listed error levels you can use with PHP in-built function “error_reporting()”. The Syntax is as “error_reporting ([int $level])”.

While defining a Custom error handler function you need to use PHP in-built library set_error_handler() function.

Trigger an Error

In Script where user inputs data use trigger_error() function to handle illegal inputs. Trigger error can be use for Server side validations.

Example of trigger_error

$myVal = 3;
if ($myVal > 2) {
trigger_error("Value must be 2 or below");

Exception Classes

While Creating a Custom Error there are following functions which can be used from Exception class.

Function Description
getMessage() This function shows exact message why error occurs. What are the possible factors generate the error.
getCode() Using getCode() we can detect the block of Code showing Error.
getFile() Shows Source File name.
getLine() This function shows in which line error occurred. It saves programmer time to locate error.
getTrace() It’s an array of the back-trace()
getTraceAsString() Presents Formatted string of Trace.