Neither of the options will actually work in the intended way (which I assume is to send a default value in case the value is not set correctly).
The following code will still throw an error if $this->getDetail
does not return an integer
public function getProperty(): int
{
return $this->getDetail('some-detail') ?? 0; // PHP prior to 7 did not support return type hints
}
The following code will catch any exceptions thrown by getDetail
but will still fail if the result is not an integer because of the : int
part.
public function getProperty(): int
{
try {
return $this->getDetail('some-detail');
} catch (Exception $e) {
return 0;
}
}
The ways that would actually work and could be debated are :
Catch the correct error you're expecting
public function getProperty(): int
{
try {
return $this->getDetail('some-detail');
} catch (TypeError $e) {
return 0;
}
}
Check if the correct return type is about to be returned:
public function getProperty(): int
{
$value = $this->getDetail('some-detail');
return is_int($value) ? $value : 0;
}
Just to note, that the exception handling is indeed slower to run when triggered but code which does not trigger exceptions (which should be most of it) runs as fast whether it's within or outside a try catch block. (Source and Source)
Personally I think this is exactly the situation where exception handling should be used: It's caused by exceptional circumstances, it's rare (I hope), and we have a way to recover from it without bringing the entire request to a halt.