catch
lacking both type annotation and trailing expr yields confusing diagnostic
#44886
Labels
C-enhancement
Category: An issue proposing an enhancement or a PR with one.
F-try_blocks
`#![feature(try_blocks)]`
If you:
catch
block, andcatch
blocks have to end in some sort of trailing expression of typeResult<.., ..>
, andResult<.., ..>
,then you are likely to end up getting an error diagnostic from the compiler that is pretty confusing.
Consider the following example:
From today's nightly, this produces the following diagnostic output (playground):
Reading that is pretty frustrating: it talks about
?
only being usable in a function that returnsResult
, but this function does returnResult
.(The error message is much improved if one actually provides a trailing expression of
Result
type in thecatch
-block; the worst-case scenario then is it just tells you to provide an explicit type annotation for thecatch
-block itself.)I assume this issue is arising because the type inference system is first using the lack of a trailing expression to infer that the type of the block's contet is
()
. Then, since we do not auto-wrapcatch
-blocks withOk
(see #41414), it concludes that the type of thecatch
expression must be()
(even though that is a nonsensical type for acatch
expression...). And then it uses that expected type (()
) as the basis for its complaints about the uses of the?
-operator.So, an idea:
Assuming we are planning to neither (1.) implement
std::ops::Try
for()
nor (2.)Ok
-wrap the trailing expression ofcatch
-blocks, then I would suggest that we forcecatch
-blocks to always have some trailing expression. That wouldn't fix every instance of this problem, but its a pretty simple change and I cannot imagine any downside (since, the way things stand, allcatch
-blocks that can reach their end always need an explicit trailing expression to compile)(To handle the more general case, we may want to consider changing how type inference is handled for
catch
-blocks. But to be honest, given how general-purposecatch
/?
are since they are overloaded via theTry
trait, I am not sure whether there is a good strategy for handling the general case here.)The text was updated successfully, but these errors were encountered: