TL;DR
My questions being :
- Is it a good practice to have exceptions inside an overriden methods ?
- If so, how should I document and handle exceptions so that PHPStan doesn't block my pipelines ?
- If not, how is the best way(s) to handle this kind of cases ?
Full context
I have some trouble regarding Handling Exception with PHPStan.
I have this abstract class :
abstract class GenericClass {
final public function handle(): void {
$this->myMethod();
}
abstract protected function myMethod(): void;
}
and this child class :
class MyClass extends GenericClass {
/**
* @throws MyException
**/
protected function myMethod(): void
{
throw new MyException();
}
}
Finally, I inject this child class inside a service class :
class ServiceClass {
private MyClass $myClass;
protected function __construct(MyClass $myClass)
{
$this->myClass = $myClass;
}
public function handle(): void
{
try {
$this->myClass->handle();
} catch(MyException $e) {
//error handling here
}
}
}
Obviously, abstract method myMethod
cannot guess what kind of exception will be thrown (if any). It all a matter of context. Only the calling Service with the corresponding class can know the context in which the exception is thrown.
However, when PHPStan run through this code, it says that my catch is a dead code because it's never thrown.
This is a simple case with not many exception thrown but on a larger scale with multiple child classes and different exceptions thrown on these overriden methods, it could be time-consuming to update PHPDoc on parent method.
How do I make PHPStan understand that it is not dead code.
I only want to add @phpstan-ignore-next-line
if no other solutions is possible.
Thanks in advance for all your replies