0

enter image description hereI am using filesystem::remove function to delete a file if a button pressed. The function throw an error when the file I want to delete is used by other program. I want to use try catch functions to catch the error and to prevent the program to crash. I tried this:

bool delete_file(std::string database_name)
{
    bool exception = false;
    database_name += ".db";
    try
    {
        fs::remove((path + database_name).c_str());
    }
    catch(...)
    {
        exception  = true;
    }
    return exception;
}

but the exception is not catched. I am not very experienced with error handling and thought that the function inside try block will not be executed if error occures and it goes to catch block, in python it works so... How to make the function to return false if exeption found and true otherwise ?

Mihai
  • 31
  • 3
  • What does "not crash" mean? How certain are you that you end up with a plain C++ exception getting thrown here, and not some other bug somewhere in your code that results in undefined behavior, and a ***real*** crash that no exception handler, or anything else for that matter, will save you from. – Sam Varshavchik Jun 23 '22 at 11:52
  • please see the image I added now, that exception interrupts my code, so I called it a crash. I want to the delete_file function to return false rather than see that error. – Mihai Jun 23 '22 at 11:57
  • "Exception" has many meanings. Nothing in that screenshot is authoritative as to whether the error is referencing a C++ exception or a hardware exception. Additionally, all questions here should have all relevant information ***in the question itself as plain text***. Code, data, or errors shown as images cannot be copy/pasted; or edited or compiled for further research and investigation. You do see the "View Details" link in the popup, do you? Shouldn't it be obvious to click there, and see if more useful information is available? Can you do that, and show that ***in plain text***. – Sam Varshavchik Jun 23 '22 at 12:03
  • Are you sure that it throws in that code snippet? The screenshot indicates that the exception is thrown somewhere in the `std::filesystem` library, but I don't see anything in the screenshot that tells me it was in `fs::remove`, and even if it was `fs::remove` there's nothing to indicate it was the specific call inside your try/catch block. Could you produce a full stack trace? Furthermore, there are overloads in `std::filesystem` that don't throw (but return an error code), and I don't think using `c_str()` to convert to C string and then back to `path` is a good idea, especially on Windows. – chris_se Jun 23 '22 at 21:16

0 Answers0