Error Handling Using PHP

When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.

  • Try − A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”.
  • Throw − This is how you trigger an exception. Each “throw” must have at least one “catch”.
  • Catch − A “catch” block retrieves an exception and creates an object containing the exception information.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …

  • An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block.
  • Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.
  • Exceptions can be thrown (or re-thrown) within a catch block.
<?php
   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';
?>

Leave a Reply

Your email address will not be published. Required fields are marked *