9780183527 [email protected]

Exception Handling in PHP is the process followed by the programmer to handle exceptions which are thrown during the program execution. Exceptions are raised when some line of code breaks and does not execute as expected. These exceptions if not caught properly will cause our application to stop which will not be a good experience for end users who are not aware of the underlying details of the application. A good programmer always write his code considering exception handling in mind.

Difference between Errors and Exceptions in PHP

  • Errors in PHP are those exceptions which cannot be handled and leads to halting of the application.
  • Errors are generally raised by the environment in which the application is running. For ex. if the memory runs out of space.
  • Errors can not be handled using try catch block.

Handling Exceptions using Try Catch Block

Exceptions in PHP are handled using try catch block in which the code where there is a possibility of the exception being raised is put into try block and the exception handling code is placed in catch block which if followed by try block.

For example:

// code before try block

try {
  // code to be executed
 
  // Something unexpected happens the the control of execution will jump to catch part
 
  // once the control is transferred to catch part the rest of the code in try block will not be executed
} catch (Exception $e) {
  // exception will be handled here
  // $e->getMessage() contains the error message
  // Exception logging can be used with the method name in which the exception has occured along with the excetion detail
}
 
// code after try block

Inside the catch block an exception object is passed which consists of the information about the exception.

Throwing an exception using throw keyword

We can also explicitly throw exceptions using the throw keyword. For example we can validate the data entered by the user and can throw exception is the data is not valid.

For example:

<?php
try {
    // store the file path in a variable
 
    $file_path = "config.php";
 
    if (!file_exists($file_path))
    {
      throw new Exception("file not found.");
    }
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}
?>

In the above example we are checking whether a config.php file exists or not if it does not exist we are throwing an exception manually which will be caught in the catch block where we are showing the error message and also stopped the execution of the application.

Try block can not stand alone it must be followed by at least one catch block. Catch blocks can also be more than one if we want to handle multiple exception types where more specific exceptions are always kept at the top and more general exception classes are kept at the bottom.

Exceptions if they are not handled in the same function in which they are thrown will be propagated further to the calling code where they can be handled.

For example:

<?php  
//function with an exception  
function checkNumber($num) {  
   if($num>=10) {  
     //throw an exception  
     throw new Exception("Value must be less than 10");  
   }  
   return true;  
}  
  
//trigger an exception in a "try" block  
try {  
   checkNumber(4);  
   //If the exception throws, below text will not be display  
   echo 'If you see this text, the passed value is less than 10';  
}  
  
//catch exception  
catch (Exception $e) {  
   echo 'Exception Message: ' .$e->getMessage();  
}  
?>

In the above code exception is being thrown from the function but the try catch block in not inside the function rather the function call is enclosed inside try catch block.

The Finally block

This block of code is used to execute code that need to executed always irrespective of the exception whether it has occurred or not.

For example:

try {
  
} catch (Exception $e) {
 
} finally {
  // code, it'll always be executed
}

Finally block is generally used to clean up the resources being used during the program like open db connections or open files etc.

Custom Exceptions in PHP

We can create our own exception classes in PHP if our requirement is not satisfied with inbuilt classes available in PHP. In order to create our own exception classes we need to create a new class that derives from the base Exception class.

<?php  
//Custom Exception classes that derives from the exception class
class DivideByZeroException extends Exception { }  
class DivideByNegativeNoException extends Exception { }  

function checkdivisor($dividend, $divisor){  
  try {  
      if ($divisor == 0) {  
        //throw object of the custom exception class
        throw new DivideByZeroException;  
      }   
      else if ($divisor < 0) {  
         throw new DivideByNegativeNoException;   
      }   
      else {  
        $result = $dividend / $divisor;  
        echo "Result of division = $result </br>";  
      }  
    }  
    catch (DivideByZeroException $dze) {  
        echo "Divide by Zero Exception! </br>";  
    }  
    catch (DivideByNegativeNoException $dnne) {  
        echo "Divide by Negative Number Exception </br>";  
    }  
    catch (Exception $ex) {  
        // if the exception is not caught in the above catch blocks than it will come here
        echo "Unknown Exception";  
    }  
}  
   
    checkdivisor(17, 3);// no exception will be thrown  
    checkdivisor(45, -6);  // Divide by negative number exception will be thrown
    checkdivisor(30, 0);  // Divide by zero exception will be thrown
?>

In the above code we are creating two custom classes that derive from the base exception class. One will be used to throw exception if the divisor is zero and other will be used to throw exception if the divisor is negative.

Function checkdivisor() is called three times to see the different error messages based on the divisor being passed to it either positive, negative or zero.