Skip to content

Exception from Future seems leaked in async generator even error catching code has been executed #45952

Open
@timnew

Description

@timnew

Not sure whether it is a bug or so, but it definitely quite surprising.

I noticed the exception from the future still bubble up even when a try catch or Future.catch was applied.

Here is some experiment I tried:

Stream<String> test1(Future<String> future) async* {
  try {
    yield "a";
    yield await future;
    yield "b";
  } catch (ex) {
    yield ex.toString();
  }
  yield "c";
}

Stream<String> test2(Future<String> future) async* {  
  yield "a";
  yield await future.catchError((ex) => ex.toString()); 
  yield "c";
}


Stream<String> test3(void Function() action) async* {
  try{
    action();
  }catch (ex) {
    yield ex.toString();
  }
}


Stream<String> test4() async* {
  try {
    yield "a";
    yield await Future.error("error");
    yield "b";
  } catch (ex) {
    yield ex.toString();
  }
  yield "c";
}

Stream<String> test5() async* {  
  yield "a";
  yield await Future<String>.error("error").catchError((ex) => ex.toString()); 
  yield "c";
}


Stream<String> test6() async* {
  try{
    throw "error";
  }catch (ex) {
    yield ex.toString();
  }
}

Future<void> printStream(Stream stream) async => print(await stream.toList());

void main()  async {
  await printStream(test1(Future.error("error")));  
  await printStream(test2(Future.error("error")));
  
  await printStream(test3(()=> throw "error"));
  await printStream(test4());  
  await printStream(test5());
  await printStream(test6());
}

I would expect the code wrong without any error.
But in practise, error was thrown from test1 and test2, but not the others.

image

Here is the intractable example: https://dartpad.dev/4bf9caaca179b50000b8abed1707a7d4?null_safety=true

Not sure is this an expected behaviour or some sorts of bug?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-documentationPrefer using 'type-documentation' and a specific area label.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions