PHP Error Handling: die, Custom error handler, Error reporting

  • Error is generated in the script whenever something went wrong with the code.
  • To handle errors in the script, a built-in error handler mechanism in PHP stops the execution of the script, and display an error message.
  • It will display the following information:
    • Error Type
    • Detailed Error Message
    • File Name
    • Line Number
  • Whenever a web page or application is designed we need to take care of such errors otherwise it will create the wrong impression on end-user and it will also stop the execution of the script.
  • PHP allows us to handle errors in a number of ways. There are three methods that are commonly used.
    • Using die() function
    • Using a Custom Error Handler
    • PHP Error Reporting

Using die() function:

  • This function will display error message that can be easily understand by user and it will also stops the execution of script.

Example:- We will here write the script which will check whether two-variable var1 & var2 are assigned any value or not using isset() function. If the value is not assigned then using die() function we will display error message & stop the execution of a script.

<?php
	if(!isset($var1) and !isset($var2)){
		die("Variables are not defined");
	}
	else{
		$sum = $var1+$var2;
		echo "Answer is:". $sum; 
	}
?>

Output:-

Variables are not defined

Using Custom Error Handler:

The second approach of error handling in PHP is defining custom error handler function. So we will simply create the function which can be called whenever the error occurs.

Syntax:-

Function custom_error_function(Error_level, Error_Message, FileName, LineNumber, Context)

Here,

Error_level: Indicates the error report level. It is mandatory.

Error_Message: Indicates detailed error description. It is mandatory.

FileName: Indicates the name of the file in which error is generated. It is optional.

LineNumber: Indicates line number in the file where error is generated. It is optional.

Context: Indicates an array that contains all the variables along with its value that is in use when an error is generated. It is optional.

Once the custom error handler function is defined, we need to set a custom error handler using set_error_handler() function.

Syntax:-

set_error_handler(Custom_Function_Name)

Once custom error handler is set, it will display custom error message whenever any error is generated in our code. But this will not stop the execution of script.

Example:-

Here we are writing script which will divide two numbers that is var1 by var2 but value of var2 is 0, so it will generate Divide by Zero error message using custom error handler.

<?php
	function CustomErrorMessage($Level, $Msg, $FileName, $LineNo, $Context){
		echo "Error Level:". $Level. "<br/>";
		echo "Error Message:". $Msg. "<br/>";
		echo "Error FileName:". $FileName. "<br/>";
		echo "Error Line Number:". $LineNo. "<br/>";
		echo "Error Context:". $Context. "<br/>";
	}
	set_error_handler("CustomErrorMessage");
	$var1 = 10;
	$var2 = 0;
	echo $var1/$var2;
	echo "Number1=". $var1. "<br/>";
	echo "Number2=". $var2. "<br/>";
?>

Output:-

Error Level: 2
Error Message: Division by Zero
Error FileName: C:\wamp\www\NotMeetingCondition.php
Error Line Number: 15
Error Context: Array
Number1= 10
Number2= 0

PHP Error Reporting:

This is third approach of error handling in PHP. PHP has built in function error_reporting function

Syntax:-

<?php
	error_reporting($reporting_level);
?>

Here,

error_reporting: It is an error reporting function.
reporting_level: It is optional and can be used to set the reporting level.

In PHP, there are totally 11 types of errors:

Reporting LevelMeaningExample
E_ERRORIt is fatal error, occurs at runtime & will terminate the execution of script.error_reporting(E_ERROR); 
E_WARNINGIt is non-fatal error, occurs at runtime but will not terminate the execution of script.error_reporting(E_WARNING); 
E_PARSEIt is syntax error, occurs at compile time, and does not allow to execute the script.error_reporting(E_PARSE); 
E_NOTICEIt is runtime notice, occurs at runtime, and will not terminate the execution of script but there will be chance of error in the code.error_reporting(E_NOTICE); 
E_CORE_ERRORIt is fatal error, occurs due to some internal problems in PHP installation.error_reporting(E_CORE_ERROR); 
E_CORE_WARNINGIt is compile time warning, occurs due to some internal problems in PHP installation.error_reporting(E_CORE_WARNING);
E_COMPILE_ERRORIt is fatal compile time error, occurs due to syntax error, and it will terminate the execution of script.error_reporting(E_COMPILE_ERROR); 
E_COMPILE_WARNINGIt is non-fatal compile time error, occurs due to syntax error, and it will not terminate the execution of script.error_reporting(E_COMPILE_WARNING); 
E_USER_ERRORIt is user generated error.error_reporting(E_USER_ERROR); 
E_USER_WARNINGIt is user generated warning.error_reporting(E_USER_WARNING); 
E_USER_NOTICEIt is user generated notice.error_reporting(E_USER_NOTICE);
  • An exception is an object that is generated in the script because of some unexpected conditions such as:
    • The user entered invalid input.
    • The file that needs to be opened does not exist or has been deleted.
    • In the middle of communication, the network connection has been lost.
  • In PHP, some of these exceptions are caused by the user’s mistake, some by programmer’s mistake, and some by physical resources.
  • When such conditions arise in the script an object is created which represents exception condition and this object is thrown by the system to the calling method. This thrown object is handled by the built-in exception handling mechanism supported by PHP.
  • The drawback of built-in exception handling is that the execution of the script is terminated when such a condition is arising.
  • It is also possible to display the description of the exception conditions without terminating the execution of the script. To do so PHP provides manual exception handling mechanism using the following three keywords:
    • Try
    • Catch
    • Throw

Syntax:-

<?php
	try{
			//block of code to be executed
			throw new Exception("Error Message");
	}
	catch(Exception $obj){
		//Exception handling code for exception
	}
?>

The detail description of each block is given below:

  • Try: In this block, the code to be executed or code that may cause an exception condition is kept. If any exception conditions arise in the try block then a new object of type exception is automatically created and throw by the try block.
  • Catch: The exception object that is thrown from the try block is caught by the catch block. The single try block can have one or multiple catch blocks.
  • Throw: The system generated exceptions are automatically thrown by the system from the try block. But if we want to generate any exception object manually then we can use throw keyword.

Example:-

Here we are writing script which will divide two numbers that is var1 by var2. The code is written inside try block. First we will check whether var2 is 0 or not. If it is 0 then we are throwing an exception object from the try block.

<?php
	try{
		$var1 = 10;
		$var2 = 0;
		if($var2 == 0){
			throw new Exception(“Divide By Zero”);
		}
		else{
			$var3 = $var1/$var2;
			echo “Answer is:” .$var3;
		}
	}
	catch(Exception $e){
		echo $e -> getmessage();
	}
?>

Output:-

Divide By Zero

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

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