Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The throw keyword in Dart is an expression used to raise an exception or error at runtime. Because Dart treats throw as an expression rather than a statement, it evaluates to the bottom type Never. This allows it to be embedded directly within other expressions, as the compiler understands that the expression will never successfully return a value to its surrounding context.

Syntax

The basic syntax consists of the throw keyword followed by an expression that evaluates to a non-null Dart object:
throw <expression>;

Technical Characteristics

1. The Never Type When a throw expression is evaluated, the current control flow is immediately interrupted. The Dart analyzer assigns the return type of a throw expression as Never. Because Never is a subtype of all other types in Dart’s sound type system, a throw expression satisfies the type checker in any context requiring a specific return type. 2. Arbitrary Object Throwing Unlike languages that restrict exceptions to specific base classes (e.g., Throwable or Exception), Dart permits the throwing of any non-null object. While typically used with instances of Exception or Error, throwing primitives or custom objects is syntactically valid.
throw FormatException('Invalid format'); // Standard exception object
throw 'String error';                    // Valid, throws a String object
throw 404;                               // Valid, throws an int object

Expression Contexts

Because throw is an expression, it can be utilized in concise syntactic constructs where standard statements are invalid. Arrow Functions It can serve as the single expression body of an arrow function.
void triggerError() => throw StateError('Invalid state');
Ternary Operators It can be used as one or both branches of a conditional expression.
int parseValue(bool isValid) {
  return isValid ? 100 : throw ArgumentError('Invalid flag');
}
Null-Aware Operators It can be placed on the right-hand side of the null-coalescing operator (??) to enforce non-nullability during assignment.
String processName(String? inputName) {
  String name = inputName ?? throw ArgumentError.notNull('inputName');
  return name;
}
Master Dart with Deep Grasping Methodology!Learn More