Skip to main content
The throw keyword is an expression that explicitly raises an exception, immediately halting the execution of the current function and initiating stack unwinding. Control is transferred to the nearest enclosing catch clause matching the thrown object’s type; if no handler is found, the current isolate terminates with an unhandled exception.

Syntax and Semantics

In Dart, throw is an expression that evaluates to the bottom type Never. This allows it to be used in contexts requiring either a statement or an expression.
throw expression;
Upon execution:
  1. The expression is evaluated.
  2. The runtime verifies the result is not null. If the operand evaluates to null (e.g., via a dynamic type), a NullThrownError is raised.
  3. Normal execution flow is interrupted.
  4. The runtime traverses the call stack to locate an exception handler.

Throwable Types

Unlike statically typed languages that restrict throws to instances of specific classes (e.g., Throwable), Dart permits the throwing of any non-null object. Standard Implementation Idiomatic Dart code throws instances of classes that implement Exception or subclass Error.
throw FormatException('Expected alphanumeric string');
throw OutOfMemoryError();
Arbitrary Objects Developers may throw primitive types or arbitrary objects, though this bypasses standard type-matching patterns in catch blocks.
throw 'A critical failure occurred'; // Throwing a String
throw 404;                           // Throwing an int

Throw as an Expression

Because throw evaluates to Never, it can be embedded within other expressions, such as arrow functions, null-coalescing operations, and conditional operators. Arrow Functions
void execute() => throw UnimplementedError();
Null-Coalescing Operator
// If 'data' is null, the right-hand side executes, throwing the error.
String value = data ?? throw ArgumentError('Data cannot be null');
Conditional Operator
int result = isValid ? calculate() : throw StateError('Invalid state');

The rethrow Keyword

While throw initiates a new exception event, the rethrow keyword is used exclusively within catch blocks to resume the propagation of the currently caught exception. Crucially, rethrow preserves the original stack trace of the exception, whereas throwing the caught object again using throw would reset the stack trace to the current line.
try {
  processData();
} catch (e) {
  // Log the error or perform partial handling
  print('Error intercepted: $e');
  
  // Resume propagation with the original stack trace
  rethrow; 
}
Master Dart with Deep Grasping Methodology!Learn More