A string or number literal is thrown instead of an Exception or Error

ID

dart.correctness.only_throw_errors

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Error Handling

Language

Dart

Description

Reports throw statements whose operand is a string, numeric or boolean literal rather than an instance of Exception or Error.

Rationale

Dart allows any object to be thrown, but every convention around error handling assumes an Exception or an Error. A thrown literal cannot be selected by an on clause, so callers have to fall back to a bare catch that intercepts everything; it carries no type, so distinguishing this failure from any other means comparing strings; and it carries no fields, so no detail beyond the message survives. Tooling that reports errors by type — logging, crash reporting, retry policies — sees String or int and cannot classify the failure.

The following code illustrates the pattern detected by this rule:

class Validator {
  void checkName(String name) {
    if (name.isEmpty) {
      // FLAGGED: A string or number literal is thrown instead of an Exception or Error
      throw 'name must not be empty';
    }
  }
}

Remediation

Throw an instance instead: ArgumentError, RangeError or StateError for a broken contract, FormatException for unparsable input, or a small class implementing Exception for a domain failure. Callers can then select it with on MyException catch (e) and read the detail from its fields.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved