PHP Nested Exception

PHPServer Side ProgrammingProgramming


Blocks of try - catch can be nested upto any desired levels. Exceptions will be handled in reverse order of appearance i.e. innermost exception processing is done first.


In following example,inner try block checks if either of two varibles are non-numeric, nd if so, throws a user defined exception. Outer try block throws DivisionByZeroError if denominator is 0. Otherwise division of two numbers is displayed.


 Live Demo

class myException extends Exception{
   function message(){
      return "error : " . $this->getMessage() . " in line no " . $this->getLine();
   if (is_numeric($x)==FALSE || is_numeric($y)==FALSE)
      throw new myException("Non numeric data");
catch (myException $m){
   echo $m->message();
if ($y==0)
   throw new DivisionByZeroError ("Division by 0");
echo $x/$y;
catch (DivisionByZeroError $e){
   echo $e->getMessage() ."in line no " . $e->getLine();


Following output is displayed

Division by 0 in line no 19

Change any one of varibles to non-numeric value

error : Non numeric data in line no 20

If both variables are numbers, their division is printed

Updated on 18-Sep-2020 09:04:43