sdk
sdk copied to clipboard
"foo ?? throw" leads to really confusing error messages
Due to precedence rules, if you use throw on the right hand side of an ?? operator you need to wrap it in parentheses.
Unfortunately, if you don't, the analyzer really doesn't help you. For example, this code:
Object foo(Object? arg) {
return arg ?? throw 'foo() expects a non-null value';
}
...generates these six messages on the same line:
error • A value of type 'dynamic' can't be returned from the function 'foo' because it has a return type of 'Object' • test.dart:2:10 • return_of_invalid_type
error • 'throw' can't be used as an identifier because it's a keyword • test.dart:2:17 • expected_identifier_but_got_keyword
error • Expected to find ';' • test.dart:2:17 • expected_token
error • Undefined name 'throw' • test.dart:2:17 • undefined_identifier
info • Avoid using unnecessary statements • test.dart:2:23 • unnecessary_statements
info • Dead code • test.dart:2:23 • dead_code
Any updates?) Still produced on flutter 3.13.6 dart 3.1.3
Not that I'm aware of.
I'll note that half of these diagnostics are produced by the parser, not by the analyzer.
The best approach would be to improve the parser to recover better in this situation. If it notices a throw in a situation where it isn't allowed because of precedence, it would be nice if it would look to see whether the addition of parentheses around the throw would result in a valid parse, and if so for it to issue a single diagnostic of the form "The 'throw' expression must be enclosed in parentheses in this location.", supply synthetic parentheses, and report the structure to the listeners as it would have had the parentheses been explicit in the input.
If that were done then I believe that none of the other 5 diagnostics would have been produced.