Should I add @throws in PHPDoc to a function using a function that throws an Exception?

For example, consider the following code:

/** * @param array $array * @param string $key * @return mixed * @throws \InvalidArgumentException */ private function getArrayEntry(& $array, $key) { if (!array_key_exists($key, $array)) { throw new \InvalidArgumentException( 'Invalid array of values for location. Missing '.$key.'.' ); } return $array[$key]; } /** * @param array $data * @return Location */ public function createFromArray(array $data) { $this->getArrayEntry($data, 'name'); } 

Should the second method have @throws in the doc block?

How is it used compared to Java, where there is the keyword 'throw'?

+8
php phpdoc
source share
1 answer

@throws should only be placed in the docBlock of the method in which the exception is thrown. If you push it onto the stack, it will be redundant and will violate the DRY principle!

In java you can choose between @throws and @ exception..see here

By the way: You are throwing the wrong type of exception. You should throw a \ OutOfBoundsException . Otherwise, it is a violation of POLA . \ InvalidArgumentException for unexpected argument type.

+4
source share

All Articles