Guide | PHP

How to Handle Exceptions in PHP

How to Handle Exceptions in PHP

Exception Handling in PHP

The try-catch

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

PHP nested try-catch

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

Catching all PHP exceptions

The simplest way to catch exceptions is through the use of a generic try-catch block. Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front:

try {
  // ...
} catch ( \Exception $e ) {
  // ...
}

Catching specific PHP exceptions

While catching every exception thrown is great for simplistic implementations—such as generalizing API error responses—best practice is to catch for specific PHP exceptions. By using the same type-hinting method shown above in reference to specific exception objects instead of a global exception object, you can react more effectively to individual problems that your application may encounter on the way.

try {
  // ...
} catch ( \Custom\Exception $e ) {
  // ...
}

Catching just one type of PHP exception isn't very valuable though, is it? What happens if your application throws a different exception? Much like an if-elseif-else chain, a try-catch block can have multiple catches—which, when combined with a check for the built-in PHP exception class, allows you to logically adapt to any and all issues that may arise:

try {
  // ...
} catch ( \Custom\Exception $e ) {
  // ...
} catch ( \Other\Exception $e ) {
  // ...
} catch ( \Exception $e ) {
  // ...
}

The exception handler

While wrapping dangerous code in try-catch blocks is a great way to harden an application against unexpected PHP errors, you can't always catch everything. Sometimes an exception falls through the cracks, which is where the global PHP exception handler comes into play. This method, dubbed set_exception_handler, provides a fallback for any uncaught exceptions.

set_exception_handler(function($exception) {
  // ...  
});

Although you can utilize this method in a number of different ways, it is generally best used for logging and display formatting, as every PHP exception thrown will be caught—not just built-in exceptions—which can result in unpredictable behavior if not used properly.

PHP framework exception handling

While the global exception handler can be used regardless of framework, it is important to know that frameworks like Symfony and Laravel have their own ways of handling PHP exceptions. Laravel, for example, handles all exceptions using a class that defines how exceptions should be reported and rendered. Symfony, on the other hand, uses an event listener to catch exceptions. Both valid ways to handle PHP exceptions, but designed to fit within their own ecosystems.

Check out our blog to see a working example of Laravel error reporting.

Track, Analyze and Manage PHP Errors With Rollbar

Managing errors and PHP 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. Learn more about Rollbar’s features for PHP and then sign up for a free trial.