Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpStorm inspection bug or bad code? Exception not thrown in try block is unexpected

I'm using PhpStorm and I'm throwing a custom exception in the parent class of a child class that I have an instance of.

I'm not catching the exception from the parent call in the child because I want catching that to be the responsibility of the code making the call on the child class instance.

PhpStorm is complaining that the caught exception is not thrown in the try block, but the method on the parent does throw it, this method is being called from the child method which is being called within the try block.

Is this a bug with the inspector or am I actually doing something wrong here?

Here is some sample code that replicates the issue:

<?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?
}

And here is a picture

screenshot

like image 870
Rick Kukiela Avatar asked Mar 21 '18 17:03

Rick Kukiela


1 Answers

When in doubt, check your comments with 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?
}

Voila, the whiny PhpStorm all of a sudden understands your code, as seen here:

enter image description here

like image 128
YvesLeBorg Avatar answered Sep 26 '22 02:09

YvesLeBorg