【问题标题】:Should I add @throws in PHPDoc to the function using function that throws Exception?我应该使用抛出异常的函数将 PHPDoc 中的@throws 添加到函数中吗?
【发布时间】:2014-03-23 12:29:07
【问题描述】:

例如考虑以下代码:

/**
 * @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');
}

第二种方法是否应该在 doc bloc 中也有@throws?

与有'throws'关键字的Java相比,它如何使用?

【问题讨论】:

    标签: php phpdoc


    【解决方案1】:

    @throws 应该只放在抛出异常的方法的 docBlock 中。 如果你把它放在堆栈上,那将是多余的,并且违反了DRY原则!

    在 java 中,您可以在 @throws 和 @exception 之间进行选择 ..see here

    顺便说一句:您抛出了错误类型的异常。你应该抛出一个\OutOfBoundsException。否则违反POLA。 \InvalidArgumentException 用于意外的参数类型。

    【讨论】:

    • 感谢 Mamuz 的精彩提示!
    • 我通常同意 Mamuz 的观点,但我也会考虑文档阅读器只会看到公共 createFromArray(),而不是私有 getArrayEntry() 的论点,所以唯一的方法是与 API 阅读器就抛出的异常进行沟通将在公共方法的文档块中显示它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2010-12-23
    • 2013-05-20
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多