Last active
August 29, 2015 14:18
-
-
Save zoechi/ce6e4718b36c605cb7fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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