Organize Code

Execption

PHP

 

Try Catch

PHP 5
function divide($a, $b) {
  try {
    print($a/$b);
  } catch(Exception $e) {
    print("Cannot divide by zero");
  }
}

Try/Catch blocks are used for handling exceptions and errors that can happen in runtime.

Put the risky part of the code inside the try block and specify what to do if an exception happens inside catch block.

Since PHP consider devide-by-zero a warning, for the sake of this and following examples, you need to set an error handler to throw an exception in case of errors:

set_error_handler(function (){
    throw new Exception('Oh no!');
});
 

Catch Specific Exception

PHP 7
function divide($a, $b) {
  try {
    print($a/$b);
  } catch(DivisionByZeroError $e) {
    print("Cannot divide by zero");
  } catch(Exception $e) {
    print($e->getMessage());
  }
}

After PHP 7.1 , You can have multiple catch blocks for better error handling.

This helps to run different error handling blocks of code for different types of exceptions.

 

Caught Exception object

PHP 5
function divide($a, $b) {
  try {
    print($a/$b);
  } catch(Exception $e) {
    print($e->getMessage());
    print($e->getCode());
    print($e->getFile());
    print($e->getLine());
    print($e->getTraceAsString());
  }
}

All the Exceptions in PHP are eventually derived from \Exception.

There are useful methods on caught exception object:

  • getMessage() - Exception message
  • getCode() - Exception code
  • getFile() - Exception filename
  • getLine() - Exception Line number
  • getTrace() - Exception stack as array
  • getTraceAsString() - Exception stack as string
 

Finally

PHP 5
function divide($a, $b) {
  try {
    print($a/$b);
  } catch(DivisionByZeroError $e) {
    print("Cannot divide by zero");
  } catch(Exception $e) {
    print("Some other error happened");
  } finally {
    print("divide function executed");
  }
}

The code inside the finally block will always be executed after the Try/Catch block.

Even if you have a return statement inside a try or catch blocks, the finally block will be run before exiting the function.

 

Throw

PHP 5
function divide($a, $b) {
  try {
    throw new Exception("Error for no reason");
  } catch(Exception $e) {
    print("Executed all the time");
  }
}

Exceptions are a great way of organizing your code runtime errors.

If you're writing a Library or any reusable code, you want to throw different exceptions when different things go wrong, so that the users of your library can do different actions in each case.

Thrown exceptions bubble up in the call stack until they are caught. If it is not caught, PHP Fatal Error happens.