Streams #3

In this lesson, you will learn to handle errors in Streams.

Handling Errors in Streams

When an error(s) occurs, a Stream can notify it as an error event similar to a data event. The stream can notify about an error in one of three ways:

  • Stream notifies the first error event and stops. We will see a few examples of this case in the lesson.
  • Stream notifies multiple error events.
  • Stream notifies error event(s) and continue delivering events.

Error handling in await for block

An error event can be responded to within the try/catch block. Let’s see the first option to handle one error event by putting an await for loop in the previous example inside the try/catch block.

To be able to see the catch block respond to the error event, we need to tweak createStream to throw an Exception at some point. Let’s assume the error event occurs when accessing the 5th number.

//Generated Stream with numbers. Added exception on purpose for demonstration
Stream<int> createNumberStreamWithException(int last) async* {
  for (int i = 1; i <= last; i++) {
    if (i == 5) {
      throw new Exception("Demo exception when accessing 5th number");
    }
    yield i; //to be able to send spaced out events
  }
}

The handlingExceptionUsingAwaitFor() is executed in the main() method.

Get hands-on with 1200+ tech skills courses.