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.
- The
expressionis evaluated. - The runtime verifies the result is not
null. If the operand evaluates tonull(e.g., via adynamictype), aNullThrownErroris raised. - Normal execution flow is interrupted.
- 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.
catch blocks.
Throw as an Expression
Becausethrow evaluates to Never, it can be embedded within other expressions, such as arrow functions, null-coalescing operations, and conditional operators.
Arrow Functions
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.
Master Dart with Deep Grasping Methodology!Learn More





