Blog |

PHP Nested Try-Catch

PHP Nested Try-Catch
Table of Contents
Try Rollbar Today

Proactively discover and resolve errors

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first. Nested blocks can be useful in case a block of code causes an exception, which can be handled within that block and program execution can continue in the outer block. They can also be useful in case the handling of an exception causes another exception.

Here is an example of a nested try-catch block:

try{
   try{
      if(file_exists("myfile.json")){
         //upload file
      } else {
         throw new Exception( 'File not found');  
      }
   }
   catch (Exception $e){
      throw new Exception( 'Unable to upload file',0,$e);
   }
   //continue outer try block code
}
catch (Exception $e){
   echo $e->getMessage() . "<br/>";
   while($e = $e->getPrevious()) {
      echo 'Previous exception: '.$e->getMessage() . "<br/>";
   }
}

In this example, a file is uploaded and it is checked whether the file exists or not prior to the upload operation. If it does not exist, an exception is thrown. This code that checks whether the file exists or not is placed within a try-catch block, which is nested within another try-catch block.

In case the file is not found, the inner block throws an 'Unable to upload file' exception, which is caught and handled by the outer block, leading to the following output:

Unable to upload file
Previous exception: File not found

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it Today!

Related Posts

See all posts

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Start continuously improving your code today.

Get Started Shape