Skip to content

Introduce throws keyword (like Swift) for marking throwable functions #4321

Open
@tilucasoli

Description

@tilucasoli

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);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions