IAm*_*aja 27 exception-handling try-catch dart
我最近偶然发现了以下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);
}
Run Code Online (Sandbox Code Playgroud)
我想知道ecatch子句中的变量是什么:
catch(e) {
...
}
Run Code Online (Sandbox Code Playgroud)
显然它是某种异常,但(1)为什么我们不需要指定它的类型,以及(2)我可以在那里添加什么来指定它的具体类型?例如,我怎么能以类似的方式处理多种类型的可能异常catchError(someHandler, test: (e) => e is SomeException)?
Ale*_*uin 33
1)Dart是一种可选的打字语言.所以类型e不是必需的.
2)您必须使用以下语法才能捕获SomeException:
try {
// ...
} on SomeException catch(e) {}
Run Code Online (Sandbox Code Playgroud)
最后catch可以接受2个参数(catch(e, s)),其中第二个参数是StackTrace.
| 归档时间: |
|
| 查看次数: |
11448 次 |
| 最近记录: |