首页 > 解决方案 > 颤振给我尝试捕捉的例外

问题描述

try {
        jsonFile.delete();
        fileExists = false;
        print("File deleted");
      } catch(e){
        print("File does not exists!");
      }

如果文件不存在,我想处理异常,但它给了我这个异常: 未处理的异常:FileSystemException:无法删除文件,路径='文件路径'(操作系统错误:没有这样的文件或目录,errno = 2) 而不是处理它并在控制台中向我发送消息,这是正常的吗?

标签: jsonflutterexceptiontry-catchdelete-file

解决方案


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 和使用它们的更多信息,请参阅此页面


推荐阅读