Posted By:
16 Mar, 2014 3:33 am PDT

Exception Handling in PHP

How to handle Exception in PHP?


When any kind of error appears in our code,Exception is used to change the normal flow of our script or program.Example:Division of a number by zero .

So we have  try,catch,throw  block to handle these exception.


//Handling exception in PHP





function divide($a) {

    if (!$a) {

        throw new Exception('Division by zero.');


    return 1/$a;


try {

    echo divide(2) . "<br>";

    echo divide(0) ;


catch (Exception $e) {

    echo 'Exception is ',  $e->getMessage(), "\n";






 /*Output of the above program is:

Exception is Division by zero.


Attachment: exception.php

This illustrate Exception Handling in PHP.

Exception in PHP can be thrown and caught .

Each try must have correseponding catch block.

Multiple catches can also be uses. 

Was it useful?  

Please login to reply to this problem.