Search code examples
jsonflutterexceptiontry-catchdelete-file

flutter give me exception on try catch


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

I want to handle the exception in case the file doesn't exist but it give me this exception: Unhandled Exception: FileSystemException: Cannot delete file, path = 'file path' (OS Error: No such file or directory, errno = 2) instead of handling it and send me a message in the console, it's normale?


Solution

  • jsonFile.delete() returns a Future, meaning it will run asynchronously and therefor not send errors to your catch block, which runs synchronously. You can await the result:

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

    Or, if you want to keep it asynchronous, you can use .catchError() on the Future to catch errors:

    try {
        jsonFile.delete()
          .then((value) => print("File deleted"));
          .catchError((error) => print("File does not exist"));
        fileExists = false;
    } catch(e){
        print("File does not exists!");
    }
    

    For more about Futures and working with them, see this page.