PHP: 'or' statement on instruction fail: how to throw a new exception?

后端 未结 7 1803
萌比男神i
萌比男神i 2020-12-06 04:30

Everyone here should know the \'or\' statemens, usually glued to an die() command:

$foo = bar() or die(\'Error: bar function return false.\');
7条回答
  •  孤街浪徒
    2020-12-06 05:09

    You can also create a custom exception class and use it's static constructor method instead of throw new Exception() construction.

    Exception class:

    class CustomException extends Exception {
      static public function doThrow($message = "", $code = 0, Exception $previous = null) {
        throw new Exception($message, $code, $previous);
      }
    }
    

    Usage:

    try {
    
      $foo = bar() or CustomException::doThrow('Problems with bar()');
      $aa = bb($foo) or CustomException::doThrow('Problems with bb()');
    
    } catch(Exception $e){
      echo $e->getMessage();
    }
    

    Note

    If you are using PHP 7 and higher - you can rename static method doThrow() to simply throw(), since in PHP 7 and higher it's allowed to use reserved keywords as method names.

提交回复
热议问题