Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amir5's avatar
Level 7

phpstan, specify function always throws

when writing /** @throws Exception */ phpstan think that function might throw exception, but how to specify that function always will throw exception?

0 likes
5 replies
amir5's avatar
Level 7

@Sergiu17 no errors, given I have this sample code:

class Test
{
    public string $type;
}

function getTest(): Test
{
    $test = new Test();
    $test->type = 'test';
    return $test;
}

$a = match (getTest()->type) {
    'test' => 'value',
};

when running phpstan on this code, it says Match expression does not handle remaining value: string. And I actually want some exception to be thrown, when I don't handle that case(which php does that), but phpstan does not allow that, so what I did to solve that phpstan error:

$a = match (getTest()->type) {
    'test' => 'value',
	default => throw new Exception('not handled case');
};

so I was curious about that, can I make a function like unreachable() and tell phpstan that this will always throw exception, because if I define the function like this and use that in default case:

/** @throws Exception */
function unreachable(): void
{
    throw new Exception('test');
}

it will consider the type of $a variable to be string|void, but that is not the case when throwing directly in default case.

amir5's avatar
Level 7

@jj15 I prefer writing default => throw new Exception('not handled case'); than writing comment...

amir5's avatar
amir5
OP
Best Answer
Level 7

I finally found an answer, I had to use never return type.

Please or to participate in this conversation.