Open
Description
Dart currently lacks a way to explicitly annotate when a function or method is capable of throwing an error. This makes it difficult to reason about error handling in larger projects or when handling error on third-party packages.
I propose introducing a throws
keyword (similar to Swift) that allows developers to declare when a function may throw, e.g.:
String parseIntStrict(String input) throws {
if (!RegExp(r'^\d+$').hasMatch(input)) {
throw FormatException("Invalid number format");
}
return int.parse(input);
}
This could help:
- Improve code clarity around exception handling
- Allow static analysis tools to give better hints (e.g., “this function might throw but isn’t in a try-catch block”)
- Make APIs safer and more self-documenting (specially community packages)
- Enable stricter opt-in safety modes (e.g., in Flutter, package:analyzer, etc.)
Brainstorm
As annotation
@throws
String parseIntStrict(String input) {
if (!RegExp(r'^\d+$').hasMatch(input)) {
throw FormatException("Invalid number format");
}
return int.parse(input);
}
like async keyword
String parseIntStrict(String input) throws {
if (!RegExp(r'^\d+$').hasMatch(input)) {
throw FormatException("Invalid number format");
}
return int.parse(input);
}