dart - Future execution leads to unhandled exception -


import 'dart:async';  void main() {   divide(1, 0).then((result) => print('1 / 0 = $result'))     .catcherror((error) => print('error occured during division: $error')); }  future<double> divide(int a, b) {   if (b == 0) {     throw new exception('division zero');   }   return new future.value(a/b); } 

currently learning how work futures in dart , got stucked on such easy example. future throws exception when user tries perform division zero. however, .catcherror doesn't handle exception. got unhandled exception stack trace instead. i'm pretty sure missing obvious can't understand exactly.

as understand, there way handle error:

divide(1, 0).then((result) => print('1 / 0 = $result'),     onerror: (error) => print('error occured during division: $error')); 

to use named optional argument - onerror. doing still leads unhandled exception.

i clarify 1 more thing. right? - difference between these 2 approaches .catcherror() handles errors thrown inner futures (futures called inside then() method of outer future) while onerror catches errors thrown outer future?

dmitry

thank you.

your error handling didn't work because error thrown in synchronous part of code. because method returns future doesn't mean in method async.

void main() {   try {     divide(1, 0)         .then((result) => print('1 / 0 = $result'));   } catch (error) {     print('error occured during division: $error');   } } 

if change divide function like

future<double> divide(int a, b) {   return new future(() {     if (b == 0) {       throw new exception('division zero');     }     return new future.value(a / b);   }); } 

you async error , async error handling works.

an easier way use new async/await

main() async {   try {     await divide(1, 0);   } catch(error){     print('error occured during division: $error');   } } 

try @ dartpad

and advantage works in both cases.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -