Dart by Example: Exceptions

1. //
2. class FoodSpoiledError extends StateError {
3. FoodSpoiledError(String msg) : super(msg);
4. }

6. class Potato {
7. int age;

9. Potato(this.age);

11. String peel() {
12. if (age > 4) {
13. throw new FoodSpoiledError('your potato is spoiled');
14. }
15. return "peeled";
16. }
17. }

19. main() {
20. var p = new Potato(7);

22. try {
23. p.peel();
24. } on FoodSpoiledError catch(_) {
25. print("nope nope nope");
26. }

28. // any non-null object can be thrown:
29. try {
30. throw("potato");
31. } catch(_) {
32. print("caught a flying potato");
33. }

35. // exceptions halt excecution
36. p.peel();
37. print('not reached');
38. }
1. $ dart exceptions.dart
2. nope nope nope
3. caught a flying potato
4. Unhandled exception:
5. Bad state: your potato is spoiled
6. #0      Potato.peel (file:///exceptions.dart:13:7)
7. #1      main (file:///exceptions.dart:36:5)
8. #2      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261)
9. #3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)

by @jryanio | source | license