Exception Handling in PHP

An exception is a logical/system error that occurs during the normal execution of a script. The exception could either be raised by the system or the program itself it the exception cannot be handled and the caller script/function needs to be informed about the same.

The use of a try…catch block

PHP5 introduces the try…catch block to trap exceptions. Look at the example below.

try {  
catch(Exception $e) {  
echo “Message : ” . $e->getMessage();  
echo “Code : ” . $e->getCode();  
function test() {  
if(some error condition) {  
throw new Exception(“Error String”,Error Code);  

In the above example, the method test() is called between the try {} block. The try{} block is the area where you will place your code that could raise an exception. Below the try{} block is the catch() {} block. The catch block expects the Exception type of object as a parameter. Within the catch() {} block you will place your logic to either fix the issue or log the error.

In the function test(), we raise an Exception using the ‘throw’ keyword. The statement following ‘throw’ is the syntax of creating a new object of Exception type. The exception class accepts two parameters. The left parameter is a string that is the error message and the right parameter is the integer error code that you wish to assign to that error.