json - 颤振给我尝试捕捉的例外
问题描述
try {
jsonFile.delete();
fileExists = false;
print("File deleted");
} catch(e){
print("File does not exists!");
}
如果文件不存在,我想处理异常,但它给了我这个异常: 未处理的异常:FileSystemException:无法删除文件,路径='文件路径'(操作系统错误:没有这样的文件或目录,errno = 2) 而不是处理它并在控制台中向我发送消息,这是正常的吗?
解决方案
jsonFile.delete()
返回一个 Future,这意味着它将异步运行,因此不会将错误发送到同步运行的 catch 块。您可以等待结果:
try {
await jsonFile.delete();
fileExists = false;
print("File deleted");
} catch(e){
print("File does not exists!");
}
或者,如果你想让它保持异步,你可以.catchError()
在 Future 上使用来捕获错误:
try {
jsonFile.delete()
.then((value) => print("File deleted"));
.catchError((error) => print("File does not exist"));
fileExists = false;
} catch(e){
print("File does not exists!");
}
有关 Futures 和使用它们的更多信息,请参阅此页面。
推荐阅读
- html - 您可以在表单 hidden_field 中将参数作为 ActionController::Parameters 对象转发吗?
- python - Keras 在时间序列数据上的 LSTM 性能不佳
- code-signing - 每个 .exe 代码签名操作都需要 Digicert USB 令牌吗?(EV代码签名证书)
- macos - docker compose on mac m1错误:功能未实现
- python - 如何在 python 中将 DateTime 对象转换为 SQL TIMESTAMP
- vba - 9 个字符后的自动换行宏
- spartacus-storefront - 当“strictTemplates”设置为“true”时,具有自定义图标类型的 cx-icon 会出错
- mysql - 如何正确组织MySQL数据库中的相关表?
- docker - 无法使用其 IP 地址连接到 docker 容器
- java - Androidstudio视图添加和删除问题