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

StackOverflow https://stackoverflow.com/questions/21943792

  •  14-10-2022
  •  | 
  •  

Frage

For example consider 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 doc bloc too?

How it is used compared to Java where there is 'throws' keyword?

War es hilfreich?

Lösung

@throws should be only placed in the docBlock of the method where the exception is thrown. If you put it up the stack it will be redundant and would be a violation of 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's a violation of POLA. \InvalidArgumentException is for an unexpected argument type.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top