我正在使用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?
}
这是一张照片
解决方法:
如有疑问,请使用PhpStorm查看您的评论:
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突然理解了您的代码,如下所示: