PHP 5+ has a different model similar to other programming languages. Release is important and provides better control over error management.

Let's explain when a new keyword is associated with a difference.

  • Try - A function that uses something different should be in the "try" block. If the exception does not start, the code will continue as normal. However when the difference causes, the difference is "thrown".
  • Throw - This is how you start something different. Each "throw" must have at least one "catch".
  • Catch - The "Catch " block detects alternatives and creates an object containing details of the transaction.


Following is the piece of code, copy and paste this code into a file and verify the result.

   try {
      $error = 'Always throw this error';
      throw new Exception($error);
      // Code following an exception is not executed.
      echo 'Never executed';
   }catch (Exception $e) {
      echo 'Caught exception: ',  $e->getMessage(), "\n";
   // Continue execution
   echo 'Hello World';

In the example above $e->getMessage function is used to receive an error message. There are the following functions that can be used from the Exception section.

  • getMessage() − message of exception
  • getCode() − code of exception
  • getFile() − source filename
  • getLine() − source line
  • getTrace() − n array of the backtrace()
  • getTraceAsString() − formated string of trace