phpexceptiontry-catchdrupal-6

Throwing exceptions in a PHP Try Catch block


I have a PHP function in a Drupal 6 .module file. I am attempting to run initial variable validations prior to executing more intensive tasks (such as database queries). In C#, I used to implement IF statements at the beginning of my Try block that threw new exceptions if a validation failed. The thrown exception would be caught in the Catch block. The following is my PHP code:

function _modulename_getData($field, $table) {
  try {
    if (empty($field)) {
      throw new Exception("The field is undefined."); 
    }
    // rest of code here...
  }
  catch (Exception $e) {
    throw $e->getMessage();
  }
}

However, when I try to run the code, it's telling me that objects can only be thrown within the Catch block.


Solution

  • Please note that this particular code example makes no sense, as you can simply remove the try-catch and have the same result:

    function _modulename_getData($field, $table) {
        if (empty($field)) {
          throw new Exception("The field is undefined."); 
        }
        // rest of code here...
    }
    

    so Exception will be thrown and can be caught or handled elsewhere.

    In case you are going to write some handling code, that may result in re-throwing the exception, you have to throw the Exception object, not a string returned by the getMessage() method:

    function _modulename_getData($field, $table) {
      try {
        if (empty($field)) {
          throw new Exception("The field is undefined."); 
        }
        // rest of code here...
      }
      catch (Exception $e) {
        if (some condition) {
            // do some handling
        } else {
            // the error is irrecoverable
            throw $e;
        }
      }
    }
    

    or if you have to do some recovery, as it is often used with database transactions: do the recovery and then re-throw:

      catch (Exception $e) {
          $db->rollback(); // rollback the transaction
          throw $e; // let the error to be handled the usual way
        }
      }