How to catch exception in flutter?

前端 未结 3 641
别跟我提以往
别跟我提以往 2020-12-31 01:06

This is my exception class. Exception class has been implemented by the abstract exception class of flutter. Am I missing something?

class FetchDataException          


        
3条回答
  •  灰色年华
    2020-12-31 01:50

    To handle errors in an async and await function, use try-catch:

    Run the following example to see how to handle an error from an asynchronous function.

    Future printOrderMessage() async {
      try {
        var order = await fetchUserOrder();
        print('Awaiting user order...');
        print(order);
      } catch (err) {
        print('Caught error: $err');
      }
    }
    
    Future fetchUserOrder() {
      // Imagine that this function is more complex.
      var str = Future.delayed(
          Duration(seconds: 4),
          () => throw 'Cannot locate user order');
      return str;
    }
    
    Future main() async {
      await printOrderMessage();
    }
    

    Within an async function, you can write try-catch clauses the same way you would in synchronous code.

提交回复
热议问题