logo
Blog single photo

how to create and throw exception in php


                        

Create new exception
new exception Syntax :- new Exception ($message)
throw exception :  throw $Exception;
Example:-



 <?php  

 function myfunction($num1,$num2,$num3){ 
      $result = $num1+$num2+$num3 ; 
      if($num1 < 5 || $num2 < 10 || $num3 < 20){ 
           throw new Exception ('Check your value'); 
      } 
      else 
      { 
           return $result; 
      } 
 } 
 echo myfunction(1,2,30); 
 ?> 

you will get an error like this

Fatal error: Uncaught exception 'Exception' with message 'Check your value' in /raidmd1/home/design/testlocation/create and use function/exception.php:6 Stack trace: #0 /raidmd1/home/design/testlocation/create and use function/exception.php(15): myfunction(1, 2, 30) #1 {main} thrown in /raidmd1/home/design/testlocation/create and use function/exception.php on line 6

Now try with [Try, throw and catch]

 <?php  
 function myfunction($num1,$num2,$num3){ 
      $result = $num1+$num2+$num3 ; 
      if($num1 < 5 || $num2 < 10 || $num3 < 20){ 
           throw new Exception ('Check your value'); 
           } 
           else 
           { 
           return $result; 
           } 
           } 
            try{ 
           echo myfunction(1,2,30); 
           } 
                catch (Exception $e){ 
                echo $e->getMessage(); 
 } 
 ?> 

Top