Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

phpdoc

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?

like image 997
Filip Górny Avatar asked Feb 21 '14 19:02

Filip Górny


People also ask

What is the use of PHPDoc?

PhpDoc, short for PhpDocumentor, is a powerful tool that allows you to easily document your code via specially formatted comments. The documentation will be available not only in the source code, but also in professional documentation extracted using either the web or command-line interface.

What is the use of @throws in Java?

The @throws tag MAY be used to indicate that Structural Elements could throw a specific type of error. The type provided with this tag MUST represent an object of the class Exception or any subclass thereof. This tag is used to present in your documentation which error COULD occur and under which circumstances.

How do I use PHPDoc in PhpStorm?

Using PHPDoc code inspections. PhpStorm provides a set of predefined code inspections targeted at PHPDoc blocks. These inspections check whether classes, methods, functions, variables, and constants are supplied with a PHPDoc comment and whether the tags in the comment match the documented item.

How do I enable comments in PHPDoc?

PHPDoc comments 1 Enable documentation comments. Open the Editor | General | Smart Keys page of the Settings/Preferences Ctrl+Alt+S . ... 2 Generate a PHPDoc block for a code construct. ... 3 Create tags in a PHPDoc comment block. ... 4 Configure formatting inside PHPDoc comments. ...


1 Answers

@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.

like image 119
Mamuz Avatar answered Oct 18 '22 20:10

Mamuz