4

Assuming the following example code:

/**
 * @method bool someMethod()
 */
class MyClass
{
    /**
     * @throws MyClassException
     */
    public function __call($method, $args)
    {
        if ($this->someCheck()) {
            throw new MyClassException();
        }
    }
}

//...
try {
    (new MyClass())->someMethod();
} catch (MyClassException $e) {  // Reported by PHPStorm as not thrown!
    // of course the exception is properly caught
}

How can I make IDE detect exceptions thrown by a methods declared with @method docblock? Wonder if this is even possible to do, if not - what are my alternatives?

It seems like @throws declared in magic methods are totally ignored in cases like this. Of course I could disable inspections but this isn't clean solution for me...

Jack'lul
  • 383
  • 1
  • 8

2 Answers2

3

It says it was possible for some time (some 2018.1.x versions if I'm reading the ticket correctly) but then it was rolled back in 2018.1.3 "due to usability concerns".

I agree with that -- not everyone will be happy to see unhandled exception warnings for every magic method call (e.g. Laravel uses that a lot) -- simply because not every magical method can throw exceptions.

Anyway: https://youtrack.jetbrains.com/issue/WI-39284 -- watch this ticket (star/vote/comment) to get notified on any progress.

LazyOne
  • 158,824
  • 45
  • 388
  • 391
2

Update 2021

It does not seem to work in the latest PhpStorm. Syntax was also removed from PSR draft, so this is probably no longer a viable solution.


Original answer

You can document exceptions for magic methods in this way:

/**
 * MyClass summary.
 * 
 * @method bool someMethod() {
 *     @throws MyClassException
 * }
 */
class MyClass {

    // ...
}

This syntax is part of PSR-5 draft. Standard is still not accepted, but it seems to work pretty well in PhpStorm.

rob006
  • 21,383
  • 5
  • 53
  • 74
  • This works *to a point* in the latest PHPStorm (2022.1.2); it applies the `@throws` to all magic methods, and includes `}` as part of the description. – amphetamachine Jun 16 '22 at 14:46