Skip to content

Instantly share code, notes, and snippets.

@zoechi
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoechi/ce6e4718b36c605cb7fb to your computer and use it in GitHub Desktop.
Save zoechi/ce6e4718b36c605cb7fb to your computer and use it in GitHub Desktop.
// SO 29378453
import 'dart:async';
main() {
// fails
// main1();
main2();
main3();
}
// async error handling doesn't catch sync exceptions
void main1() {
divide(1, 0).then((result) => print('(1) 1 / 0 = $result'))
.catchError((error) => print('(1)Error occured during division: $error'));
}
Future<double> divide(int a, b) {
// this part is still sync
if (b == 0) {
throw new Exception('Division by zero');
}
// here starts the async part
return new Future.value(a/b);
}
// async error handling catches async exceptions
void main2() {
divideFullAsync(1, 0).then((result) => print('(2) 1 / 0 = $result'))
.catchError((error) => print('(2) Error occured during division: $error'));
}
Future<double> divideFullAsync(int a, b) {
return new Future(() {
if (b == 0) {
throw new Exception('Division by zero');
}
return new Future.value(a / b);
// or just
// return a / b;
});
}
// async/await allows to use try/catch for async exceptions
main3() async {
try {
print('(3)');
await divideFullAsync(1, 0);
} catch(error){
print('(2) Error occured during division: $error');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment