5

I have code similar to:

  timer = new Timer(new Duration(milliseconds: 1000), () => (throw new TimeoutException('Callback not invoked!')));

  while (timer.isActive){
    await new  Future.delayed(const Duration(milliseconds: 1), () => "1");
  }
  print('this should not be reached if the exception is raised');

elsewhere I have an async callback which calls:

timer.cancel();

In the case where the callback is invoked it works fine because the callback cancels the timer.

However, I'm not really sure how to actually catch the TimeoutException in this case if it is not canceled, because it seems the exception is raised in a different scope than my main function. This means program execution continues even though

Is there a way to do some sort of try/catch or somehow handle the above timeout exception? Or a better way to do what I am trying to do?

Using dart 1.19.1.

enderland
  • 13,825
  • 17
  • 98
  • 152
  • Are you sure you need the `Timer`? What about using `Future.delayed().timeout...`? – Günter Zöchbauer Dec 09 '16 at 16:56
  • @GünterZöchbauer if that is a better option I'm more than willing to use it. I was originally using the timer because I can actually track how long the entire callback takes but wasn't able to get that working with a future based operation. – enderland Dec 09 '16 at 16:57

1 Answers1

8

You get different behavior depending on whether the timeout is 500ms or 1500ms:

   final timer = new Future.delayed(const Duration(milliseconds: 1000), 
         () => (throw new Exception('Callback not invoked!')))
     .timeout(const Duration(milliseconds: 500));
   try {
     await timer;
   } on TimeoutException catch(e) {
     print('this should not be reached if the exception is raised');
   } on Exception catch(e) {
     print('exception: $e');
   } 

DartPad

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • How can I cancel the timer future in my other callback? Previously I could just `timer.cancel()` which worked, but I'm not clear how to resolve the future here prior to the timeout occurring from another callback? – enderland Dec 09 '16 at 17:21
  • I see. Didn't think of that. I don't think there is a way to cancel a `Future`. See also http://stackoverflow.com/questions/17552757/is-there-any-way-to-cancel-a-dart-future, https://github.com/dart-lang/sdk/issues/1806 – Günter Zöchbauer Dec 09 '16 at 17:23