このページはまだ翻訳されていないため、英語で表示されます。 翻訳に参加する

throwError

Returns a unary function that always throws — for slots that expect a function, not a statement.

Never Function(T) throwError<T>(Object Function(T) toError)

Lecture

throw is a statement in Dart, so you can't drop it directly into a spot that expects a function value. throwError(toError) solves that: give it a function that builds an Object (an exception or error) from the offending value, and you get back a Never Function(T) you can pass anywhere a callback is expected — most commonly as the orElse of cases, to turn "nothing matched" into a hard failure instead of a silent fallback.

Because the return type is Never, calling it always throws; it never actually returns a value of type T. Wrap any call site in try/catch if you want to recover instead of letting the error propagate.

Demo 1 · Basics

Demo 2 · As the fallback of cases

Instead of silently falling through, throwError makes an unmatched value a loud, catchable failure:

Try it yourself

Exercise: build a throwing function for "not implemented" and trigger it.

Related: throwIf — throw conditionally, without a separate builder function · cases — the usual home for throwError as orElse · when / unless — conditional transforms that don't throw · find — returns null instead of throwing on no match