Throwing exceptions in a PHP Try Catch block

后端 未结 5 1922
情书的邮戳
情书的邮戳 2020-12-24 00:04

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

相关标签:
5条回答
  • 2020-12-24 00:42

    Just remove the throw from the catch block — change it to an echo or otherwise handle the error.

    It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.

    In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.

    A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.

    0 讨论(0)
  • 2020-12-24 00:53
    function _modulename_getData($field, $table) {
      try {
        if (empty($field)) {
          throw new Exception("The field is undefined."); 
        }
        // rest of code here...
      }
      catch (Exception $e) {
        /*
            Here you can either echo the exception message like: 
            echo $e->getMessage(); 
    
            Or you can throw the Exception Object $e like:
            throw $e;
        */
      }
    }
    
    0 讨论(0)
  • 2020-12-24 00:55
    throw $e->getMessage();
    

    You try to throw a string

    As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

    0 讨论(0)
  • 2020-12-24 00:58

    To rethrow do

     throw $e;
    

    not the message.

    0 讨论(0)
  • 2020-12-24 00:59

    Throw needs an object instantiated by \Exception. Just the $e catched can play the trick.

    throw $e
    
    0 讨论(0)
提交回复
热议问题