Dart by Example: Exceptions

  1. //
  2. class FoodSpoiledError extends StateError {
  3. FoodSpoiledError(String msg) : super(msg);
  4. }
  5. class Potato {
  6. int age;
  7. Potato(this.age);
  8. String peel() {
  9. if (age > 4) {
  10. throw new FoodSpoiledError('your potato is spoiled');
  11. }
  12. return "peeled";
  13. }
  14. }
  15. main() {
  16. var p = new Potato(7);
  17. try {
  18. p.peel();
  19. } on FoodSpoiledError catch(_) {
  20. print("nope nope nope");
  21. }
  22. // any non-null object can be thrown:
  23. try {
  24. throw("potato");
  25. } catch(_) {
  26. print("caught a flying potato");
  27. }
  28. // exceptions halt excecution
  29. p.peel();
  30. print('not reached');
  31. }
  32.  
  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