Sub*_*ick 5 php exception-handling phpstorm
我正在使用 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?
}
Run Code Online (Sandbox Code Playgroud)
这是一张图片
如有疑问,请使用 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?
}
Run Code Online (Sandbox Code Playgroud)
瞧,发牢骚的 PhpStorm 突然明白了你的代码,如下所示: