我非常喜欢PhpStorm检测工具。他们帮助我编写更好的代码。现在我有以下情况,我问自己处理这种情况的最佳方法是什么。
我有一个带有一些前置条件的函数f,例如,如下面的代码:
/**
* @param int $x
* @throws PreconditionException x is negative
*/
public function f(int $x): int
{
if ($x < 0) {
throw new PreconditionException("the input x is negative");
}
}
然后我在某个地方使用这个功能让我们说:
f(5);
现在,PhpStorm用“未处理的异常”警告我。但在这种情况下,我知道不会抛出异常,所以添加一个try块并不是真的有意义。我应该简单地忽略这个警告,或者最好的方法是什么?
答案 0 :(得分:4)
从phpStorm版本2018.1,您可以排除分析中的任何异常。转到preferences->Languages & Frameworks->PHP
并打开Analysis
标签。
您可以在此处向Unchecked Exceptions
列表
答案 1 :(得分:3)
@noinspection
标签可用于指示PhpStorm禁止检查。
标签可以在<?php
字之后的行上方,方法上方或文件顶部使用:
/** @noinspection PhpDocMissingThrowsInspection */
/**
*
* Cancels order.
*
* @return bool
*/
public static function cancel()
{
if (!self::inProgress()) return false;
/** @noinspection PhpUnhandledExceptionInspection*/
static::current()->delete();
return true;
}
可以在以下要点找到检查清单:https://gist.github.com/discordier/ed4b9cba14652e7212f5
您也可以通过界面禁用它。 ALT + ENTER ,然后向右箭头和Suppress ...
答案 2 :(得分:2)
正确的方法是将@throws
标记添加到文档(PhpStorm manual)中。
例如:
/**
* @param $userId
* @return array|null
* @throws \Exception <---------------------------
*/
public static function send($userId)
{
if (empty($userId)) {
throw new \Exception("User ID is missing", 1);
}
// ...
}
答案 3 :(得分:0)
对我有用的是将@throws
设置为Null
示例:
/**
* @return SomeObject
* @throws Null
*
*/