Joh*_*ter 34 try-catch catch-block dart flutter
鉴于下面的短代码示例:
...
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} on Exception catch (_) {
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
Run Code Online (Sandbox Code Playgroud)
我希望在解码失败时执行 catch 块。但是,当返回错误响应时,终端会显示异常,并且不会触发 catch 和继续代码......
flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?
Rém*_*let 42
函数可以抛出任何东西,甚至不是Exception
:
void foo() {
throw 42;
}
Run Code Online (Sandbox Code Playgroud)
但是on Exception
子句的意思是你特别醒目只的子类Exception
。
因此,在以下代码中:
try {
throw 42;
} on Exception catch (_) {
print('never reached');
}
Run Code Online (Sandbox Code Playgroud)
将on Exception
永远不会达到。
Ovi*_*diu 35
on Exception catch
正如其他人所回答的那样,这不是语法错误。但是,您需要注意,除非抛出的错误类型为 ,否则不会触发捕获Exception
。
如果你想找出你得到的错误的确切类型,删除on Exception
以便捕获所有错误,在 catch 中放置一个断点并检查错误的类型。您还可以使用类似于以下的代码,如果您想为异常做一些事情,并为所有其他类型的错误做一些其他的事情:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Run Code Online (Sandbox Code Playgroud)
小智 10
使用:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Run Code Online (Sandbox Code Playgroud)
您示例中的try
/catch
是同步的,而异常是异步抛出的。如果您将函数标记为异步并在返回之前等待未来,您将按预期捕获异常:
Future<http.Response> foo(url, headers) async {
try {
return await http.get(url, headers: headers);
} catch (e) {
print(e);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
规则是,异常处理应该从详细异常到一般异常,以便使操作落入正确的 catch 块中,并为您提供有关错误的更多信息,例如以下方法中的 catch 块:
Future<int> updateUserById(int userIdForUpdate, String newName) async {
final db = await database;
try {
int code = await db.update('tbl_user', {'name': newName},
whereArgs: [userIdForUpdate], where: "id = ?");
return code;
}
on DatabaseException catch(de) {
print(de);
return 2;
}
on FormatException catch(fe) {
print(fe);
return 2;
}
on Exception catch(e) {
print(e);
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} catch (_) { . // <-- removing the on Exception clause
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
Run Code Online (Sandbox Code Playgroud)
这确实有效,但这背后的理由是什么?类型不一致不是异常吗?
归档时间: |
|
查看次数: |
73245 次 |
最近记录: |