PHP Nested Exception


Introduction

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.

Example

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.

Example

 Live Demo

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

Output

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

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements