【问题标题】:PhpStorm inspection bug or bad code? Exception not thrown in try block is unexpectedPhpStorm 检查错误或错误代码? try 块中未抛出的异常是意外的
【发布时间】:2018-03-21 17:51:23
【问题描述】:

我正在使用 PhpStorm,并且我在我有一个实例的子类的父类中抛出了一个自定义异常。

我没有从子类中的父调用中捕获异常,因为我希望将其作为对子类实例进行调用的代码的责任。

PhpStorm 抱怨捕获的异常没有在 try 块中抛出,但是父级的方法确实抛出了它,这个方法是从 try 块中调用的子方法调用的。

这是检查员的错误还是我真的在这里做错了什么?

下面是一些复制问题的示例代码:

<?php

class testE extends \Exception {
}


class parentClass {

    public function testMethod() {
        throw new testE('test exception');
    }
}

class childClass extends parentClass {

    public function doSomething() {
        $this->testMethod();
    }
}

$test = new childClass;
try {
    $test->doSomething();
} catch(testE $e) {
    //   ^--- why does this report no throw in try?
    // Exception 'testE' is never thrown in the corresponding try block
    // Will this still work even though phpstorm complains?
}

这是一张照片

【问题讨论】:

  • IDE 在抛出的异常深度为 2 级时依赖注释。没有注释只检查第一级。因此,如果您将$test-&gt;doSomething(); 替换为$test-&gt;testMethod();,则不会报告此类问题(因为您将直接调用testMethod()(第一级))。使用建议的解决方案查看答案。

标签: php exception-handling phpstorm


【解决方案1】:

如有疑问,请使用 PhpStorm 检查您的 cmets:

class testE extends \Exception
{
}

class parentClass
{

    /**
     * @throws testE      <- added this
     */
    public function testMethod()
    {
        throw new testE('test exception');
    }
}

class childClass extends parentClass
{

    /**
     * @throws testE          <- added this 
     */
    public function doSomething()
    {
        $this->testMethod();
    }
}

$test = new childClass;
try {
    $test->doSomething();
} catch (testE $e) {
    //   ^--- why does this report no throw in try?
    // Exception 'testE' is never thrown in the corresponding try block
    // Will this still work even though phpstorm complains?
}

瞧,发牢骚的 PhpStorm 突然理解了您的代码,如下所示:

【讨论】:

  • 非常感谢!
  • @SublymeRick ... Bienvenido! PhpDocs 在编码时为您提供帮助,PhpStorm :) !大量使用
  • 在尝试这个之后我仍然有这个问题 - 除了它现在在 phpdoc 以及 catch 语句中
猜你喜欢
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多