PHP try catch - Exception Handling

simply php exception handling mechanism can change the normal flow of the code execution, if the specified error occurs.

php exception handling mechanism to improve your application's security, appearance, debugging capabilities, and make more robust.


PHP Exception class

exception is the base class for all exceptions.

the exception class offers six different methods to access information about what caused the problem look methods:

methoddescription
getmessage()returns the exception message
getcode()returns the exception error code
getline()returns the line number in which the exception occurred
getfile()returns the file in which the exception occurred
gettrace()gets the stack trace
gettraceasstring()gets the stack trace as a string

php try . . . catch and throw

exceptions are represented in php by the class exception or any of its subclasses.

try :- the code that may throw an exception is placed within the try block. each try must have at least one corresponding catch or finally block (or one of both).

catch:- the code to handle the exception is placed within the catch block.multiple catch blocks can be used to catch different classes of exceptions.

throw : trigger an exception. thrown object must be an instance of the exception class or a subclass of exception.

note : when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present will continue after that last catch block defined in sequence.

note : if an exception is not caught, a php fatal error will be issued with an "uncaught exception" message.

note : the finally block only work in php 5.5 and later versions.

syntax: there are three forms of the 'try' statement:

try{
   
           //throw__ statement
}
catch(exception e){
    
          // catch___statement
}     
catch{
       
          // finally__statements 
      
   }                
try
   { 
      
      //throw__ statement
      
    }
     catch(exception e){
    
    
    // catch___statement

                    }
try
   {
   
      //try __ statements
}
 finally
        {
    
   //finally___statement

       }
<?php
     
     function   exc( $value ){
             
     if( $value <= 0 ){  throw new exception("the value is less then zero");
                                                                     
                            //if value is less than 0 the exc method throw an exception 
                         }
                  }
                                           
            try{
            
                   exc(-23); //trigger exception in the try block
                   
echo "statement execute only when the exc method not throw the exception";                                                        
                                                                  
                 }catch( exception $e){
                                  
                                       echo "exception handler correct exception";
                                                            
                                       echo "<br/>error message :- ". $e->getmessage();
                                            
                                     }
?>
output: exception handler correct exception
           error message :- the value is less than zero

example explained :

the exc() method is called in a 'try' block, first the exc() method check the value, if value is less then zero then exception is thrown. the catch block retrives the exception and creates an object ($e) containing the exception information. the error message access from the exception object by calling $e->getmessage().


top level exception handler

the set_exception_handler() function is used to sets the default exception handler if an exception is not caught within a try/catch block.

             set_exception_handler( "handler" )
  • handler : name of the function to called when an uncaught exception occurs.

note : this function must be defined before calling set_exception_handler().

the handler function needs to accept one parameter, which will be the exception object that was thrown.

   <?php
     
               function   handler( $exception ){
               
                     echo  "i am exception handler";
                     
                     echo  "<br/>error message :- ". $exception->getmessage();
                     
                    }
                    
                       set_exception_handler( 'handler' );
                       
                       throw   new exception("filenotfoundexception");    
   ?>

php custom exception handler

you can extend the exception class itself to create your own custom exceptions.

this allows you to add your own methods and properties to your exception objects, which can help to make your error reporting even more rich and useful to users and developers of your applications.

     <?php
   
             class   divisionbyzero  extends   exception{
             
 public function    displaymessage(){  
 
                              $value  ="error message :- " . $this->getmessage();
                              
                              return $value; }
                              
 public function   file(){   $v  = "file path :- " . $this->getfile();
 
                                   return   $v; }                              
                        
            }
                      
             $var = -2 ;  $msg = "division by zero exception";
             
             try{   if($var<0){
             
                                     throw  new  divisionbyzero($msg);          
                        
                     }}catch(divisionbyzero $e){
                     
                                       echo    $e->displaymessage();
                                          
                                       echo    "<br/>". $e->file();
                                       
                                   }
                                   
           ?>

note : catch the exceptions always in order from bottom to the top of the exception and subclasses class hierarchy. if you have class top extending exception class, and class subtop extending class top, always catch subtop before top. look this example:

     <?php 
               class  top  extends exception{  }
               
               class  subtop  extends top{  }
               
               try{ if( 20 < 24 ){
               
                                 throw  new  subtop("subtop exception class object");
                                 
                                }
               }catch( subtop $e){ // catch only subtop exception class object
                           
                      echo  "error message : ". $e->getmessage(); }
                                     
                catch( top $e){//can catch subtop and top class exception objects
                            
                      echo  "error message : ". $e->getmessage(); }
                                         
                catch( exception $e){ //can catch all exception objects
                            
                      echo  "error message :". $e->message();  }
    ?>

php rethrowing exceptions

the php allow re-thrown an exception within a catch block.

note :- you can use a try . . catch block within another try . . . catch block.

     <?php
     
              class  top  extends   exception {}
              
              class  subtop  extends top {}
              
try{

        try{ 
                $msg = "subtop exception class object";
                                      
                throw  new  subtop( $msg );
            }
             catch( subtop $e){
                                    
                          echo  "subtop error message :- ". $e->getmessage();
                                         
                          echo  "<br/>line number :- ". $e->getline();
                                         
  throw  new  top("top exception object"); // this statement rethrow an exception
     
    } 
 
 }
  catch(top $e){
               
                       echo  "<br/>top class error message :- ". $e->getmessage();
                      
                       echo  "<br/>line number :- ". $e->getline();
                 }
   ?>