【问题标题】:flutter give me exception on try catch颤振给我尝试捕捉的例外
【发布时间】:2021-09-03 13:40:53
【问题描述】:
try {
jsonFile.delete();
fileExists = false;
print("File deleted");
} catch(e){
print("File does not exists!");
}
我想在文件不存在的情况下处理异常,但它给了我这个异常:
未处理的异常:FileSystemException:无法删除文件,路径 = '文件路径'(操作系统错误:没有这样的文件或目录,errno = 2)
而不是处理它并在控制台中向我发送消息,这很正常吗?
【问题讨论】:
标签:
json
flutter
exception
try-catch
delete-file
【解决方案1】:
jsonFile.delete() 返回一个 Future,这意味着它将异步运行,因此不会将错误发送到同步运行的 catch 块。你可以等待结果:
try {
await jsonFile.delete();
fileExists = false;
print("File deleted");
} catch(e){
print("File does not exists!");
}
或者,如果你想保持异步,你可以在 Future 上使用.catchError() 来捕获错误:
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 及其合作的更多信息,请参阅this page。