【问题标题】:Dart catch clause飞镖捕捉子句
【发布时间】:2014-01-15 04:42:53
【问题描述】:

我最近偶然发现了以下 Dart 代码:

void doSomething(String url, String method) {
    HttpRequest request = new HttpRequest();

    request.open(method, url);
    request.onLoad.listen((event) {
        if(request.status < 400) {
            try {
                String json = request.responseText;
            } catch(e) {
                print("Error!");
            }
        } else {
            print("Error! (400+)");
        }
    });

    request.setRequestHeader("Accept", ApplicationJSON);
}

我想知道 catch 子句中的 e 变量是什么:

catch(e) {
    ...
}

Obviously its some sort of exception,但是(1)为什么我们不需要指定它的类型,以及(2)我可以在那里添加什么来指定它的具体类型?例如,如何以类似于catchError(someHandler, test: (e) =&gt; e is SomeException) 的方式处理多种可能的异常?

【问题讨论】:

    标签: exception-handling try-catch dart


    【解决方案1】:
    1. Dart 是一种可选的类型化语言。所以e的类型不是必须的。

    2. 您必须使用以下语法仅捕获 SomeException

    try {
      // ...
    } on SomeException catch(e) {
     //Handle exception of type SomeException
    } catch(e) {
     //Handle all other exceptions
    }
    

    catch section of Dart: Up and Running

    最后catch 可以接受2 个参数(catch(e, s)),其中第二个参数是StackTrace

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2015-07-18
      • 1970-01-01
      相关资源
      最近更新 更多