How to handle error given by filesystem::remove function in c++? - c++

I 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 ?

Related

C++ Else statement in Exception Handling

I would like to know if there is an else statement, like in python, that when attached to a try-catch structure, makes the block of code within it only executable if no exceptions were thrown/caught.
For instance:
try {
//code here
} catch(...) {
//exception handling here
} ELSE {
//this should execute only if no exceptions occurred
}
The concept of an else for a try block doesn't exist in c++. It can be emulated with the use of a flag:
{
bool exception_caught = true;
try
{
// Try block, without the else code:
do_stuff_that_might_throw_an_exception();
exception_caught = false; // This needs to be the last statement in the try block
}
catch (Exception& a)
{
// Handle the exception or rethrow, but do not touch exception_caught.
}
// Other catches elided.
if (! exception_caught)
{
// The equivalent of the python else block goes here.
do_stuff_only_if_try_block_succeeded();
}
}
The do_stuff_only_if_try_block_succeeded() code is executed only if the try block executes without throwing an exception. Note that in the case that do_stuff_only_if_try_block_succeeded() does throw an exception, that exception will not be caught. These two concepts mimic the intent of the python try ... catch ... else concept.
Why not just put it at the end of the try block?

Exception handling, WinRT C++ concurrency async tasks

I have to implement an async HTTP GET in C++ and we have to be able to submit the app to the Windows 8 Store.
My problem is the following:
I've found a suitable Sample code which implements an HttpRequest class http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664
This example works if the URI is correct but throws an exception if the URI points to an invalid / non existing place (like: www.google22.com). This would be fine if I could catch the exception but I cannot figure it out how or where should I catch it.
Now some code.
This is the call to the async, concurrency::task based method which throws the exception:
try {
...
Web::HttpRequest httpRequest;
httpRequest.GetAsync(uri, cancellationTokenSource.get_token())
.then( [] (concurrency::task<std::wstring> response)
{
try {
response.get();
}
catch( ... ) {
int i = 1;
}
return response;
})
...
} catch ( ... ) {
...
}
And this is the relevant segment of the GetAsync method (the end of the method):
// Return a task that completes when the HTTP operation completes.
// We pass the callback to the continuation because the lifetime of the
// callback must exceed the operation to ensure that cancellation
// works correctly.
return completionTask.then([this, stringCallback](tuple<HRESULT, wstring> resultTuple)
{
// If the GET operation failed, throw an Exception.
CheckHResult(std::get<0>(resultTuple));
statusCode = stringCallback->GetStatusCode();
reasonPhrase = stringCallback->GetReasonPhrase();
return std::get<1>(resultTuple);
});
The CheckHResult line throws the exception, it's code:
inline void CheckHResult(HRESULT hResult)
{
if (hResult == E_ABORT)
{
concurrency::cancel_current_task();
}
else if (FAILED(hResult))
{
throw Platform::Exception::CreateException(hResult);
}
}
I have a try-catch around the GetAsync call and I also have a try-catch in the .then continuation lambda.
In the relevant Microsoft documentation ( http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx ) it states that exceptions thrown by a task should be catchable in the next task in the chain but somehow it doesn't work in my case. Additionally not even the try-catch around the whole call catches the exception, it just slips through everything...
Anyone had this problem? I think I've tried everything stated in the official documentations but it still lets the exception go berserk and crash the app. What do I miss?
EDIT:
I've modified the code to do nothing else but exception handling and it still doesn't catch the exception thrown by the task in .GetAsync
Cleaned-up code:
try
{
Windows::Foundation::Uri^ uri;
uri = ref new Windows::Foundation::Uri( uri_string_to_fetch );
concurrency::cancellation_token_source cancellationTokenSource = concurrency::cancellation_token_source();
Web::HttpRequest httpRequest;
OutputDebugString( L"Start to fetch the uri...\n" );
httpRequest.GetAsync(uri, cancellationTokenSource.get_token())
.then([](concurrency::task<std::wstring> response)
{
try {
response.get();
}
catch( ... ) {
OutputDebugString(L"unknown Exception");
}
})
.then([](concurrency::task<void> t)
{
try {
t.get();
// .get() didn't throw, so we succeeded.
}
catch (Platform::Exception^ e) {
// handle error
OutputDebugString(L"Platform::Exception");
}
catch (...) {
OutputDebugString(L"unknown Exception");
}
});
}
catch (Platform::Exception^ ex) {
OutputDebugString(L"Platform::Exception");
errorCallback(-1);
}
catch ( ... ) {
OutputDebugString(L"unknown Exception");
errorCallback(-2);
}
This still gives me a crash with the exception message: First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x077EEC28. HRESULT:0x800C0005
Additionally when I put some breakpoints in the code it shows that the exception slips through everything before the first .then would be called. I've put breakpoints in these locations (in the simplified / cleaned up code):
before the GetAsync call
into the GetAsync, to the CheckHResult(std::get<0>(resultTuple)); line which throws the exception
into every try and catch case / block
Order of execution, tested with breakpoints:
before the GetAsync call [OK]
in the GetAsync, the line which will throw the exception [OK]
now the app crashes, slips through every try-catch, continue
now the line in the first .then gets called, in it's try block
another app level exceptions not catched by any catch block
now the first .then's catch block
second .then method's try block
and nothing more, the second .then's catch doesn't even catch any exception
And the printed debug logs, in order:
- Start to fetch the uri...
- First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x082FEEF0. HRESULT:0x800C0005
- First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000.
- First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x082FE670. HRESULT:0x800C0005
- First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x082FDD88. HRESULT:0x800C0005
- unknown Exception
What is happening??
In the Concurrency Runtime any unhandled exception that occurs during the execution of a task is deferred for later observation. In this way, you could add a task based continuation at the end of the chain and handle errors there.
Something like this:
httpRequest.GetAsync(uri, cancellationTokenSource.get_token())
.then([](concurrency::task<std::wstring> response)
{
try {
response.get();
}
catch( ... ) {
int i = 1;
}
return response;
})
.then([](concurrency::task<void> t)
{
try {
t.get();
// .get() didn't throw, so we succeeded.
}
catch (Platform::Exception::CreateException^ e) {
// handle error
}
});
The call to .get triggers any exceptions that were raised in the task chain (if any).
For more details you can read Exception Handling in the Concurrency Runtime.
This related thread may have a clue:
Visual C++ Unmanaged Code: Use /EHa or /EHsc for C++ exceptions?
If you want to catch all the asynch exceptions you can try to set your Configuration Properties-> C/C++ -> Code Generation property to "Yes with SEH exceptions (/EHa)"

Exception not propagating properly across threads using boost::future/boost::promise

I have the following code I have simplified:
Thread two:
boost::unique_future<void> future;
TaskPtr task(new task::ReloadConfig(future));
Listener::PushTask(task);
future.wait();
try
{
future.get();
}
catch (const cfg::ConfigError& e)
{
return cmd::Result::Okay;
}
Thread two:
try
{
cfg::UpdateShared(std::shared_ptr<cfg::Config>(new cfg::Config(configFile)));
}
catch (...) // should be cfg::ConfigError
{
promise.set_exception(boost::current_exception());
return;
}
promise.set_value();
Instead of a the Cfg::ConfigError exception or one of its derived exceptions being propogated from thread two to thread one I get the following:
terminate called after throwing an instance of
'boost::exception_detail::clone_impl'
what(): std::exception
Seems this other person had similar troubles and no answer:
https://stackoverflow.com/questions/10857834/how-to-use-boostfuture-get-to-get-user-defined-exception
I also get the following error if I try to use boost::enable_current_exception:
/usr/local/include/boost/exception/exception.hpp:419:20: error: no
matching function for call to 'std::runtime_error::runtime_error()'
I can get the code working fine without exceptions, by just returning a boolean value, but this is a compromise.
I would try to do something like that in your thread two:
catch (const cfg::ConfigError& e)
{
promise.set_exception(boost::make_exception_ptr(e));
}
Otherwise if you want that current_exception() to work you have to mess with things like:
throw boost::enable_current_exception(cfg::ConfigError("meh"));

Catch block doesn't want to catch thrown exception

I have a code:
void Engine::count(const std::set<boost::filesystem3::path>& files)
{
for (auto e : files)
{
try
{
count_(e);
}
catch (const Bad_formatting& ) // Here I'm trying to catch this exception
{//but debugger never stops on this line even though breakpoint is set
throw; // and re-throw it
}
}
}
Then there is this count_ function:
void Engine::count_(const boost::filesystem3::path& file)
{
// and somewhere along this lines I'm throwing Bad_Formatting:
if (something)
{
}
else
{
throw Bad_formatting(file,"No end of multicomment found.");
}
}
But after throwing this exception, I'm getting dialog telling me that my application requested runtime to terminate in an unusual way...
The exception is never cought. Why? Does the fact that both of those fncs are static has anything to do with it? Or the fact that I'm using Qt?
EDIT:
This is the code which calls count:
try
{
Engine::count(files);
}
catch (const Bad_formatting& e)
{
QMessageBox::warning(nullptr,"Bad Formatting",msg);
}
////
struct Bad_formatting : public std::runtime_error
{
private:
boost::filesystem3::path file_name_;
public:
Bad_formatting(boost::filesystem3::path file_name,
const char* msg):std::runtime_error(msg),
file_name_(file_name)
{
}
const boost::filesystem3::path& file_name()const
{
return file_name_;
}
~Bad_formatting()throw()
{/*eb*/}
};
From the code you show you
throw an exception;
catch it;
rethrow it;
never catch it again.
Item 4 seems to be the important part.
What compiler/toolchain/debugger are you using? If you are using GCC you can use the catch throw and catch catch commands to add breakpoints on exception throwing/catching.
As of the possible reasons that it is not being caught, if the only code in the catch block is a throw, the compiler might have optimized the whole block away. Consider adding any instruction to the block (note any might require some instruction with actual side effects, or the compiler might also optimize that away)

Exception handling , unable to understand :(

Hya advance users of SO,
First of all I am new to C++, so pardon me if I don't make myself clear asking question. I've seen a example of exception handling, but couldn't figure out what's happening here :(
http://codepaste.net/zqsrnj
or
enum ErrorCode {…}; // this is exception class
ErrorCode dispatcher() {
try {
throw; // what is thrown here in function?, if rethrow what is rethrown?
}
catch (std::bad_alloc&) {
return ErrorCode_OutOfMemory;
}
catch (std::logic_error&) {
return ErrorCode_LogicError;
}
catch (myownstdexcderivedclass&) {
return ErrorCode_42;
}
catch(...) { // this will handle the above throw in try block of dispatcher
return ErrorCode_UnknownWeWillAllDie;
}
}
ErrorCode apifunc() {
try {
// foo() might throw anything
foo();
}
catch(...) {
// dispatcher rethrows the exception and does fine-grained handling
return dispatcher();
}
return ErrorCode_Fine; //
}
ErrorCode apifunc2() {
try {
// bar() might throw anything
bar();
}
catch(...) {
return dispatcher();
}
return ErrorCode_Fine;
}
Can anyone explain this line by line or overall what's happening here, how control is flowing? Any help is very much appreciated, so thanks a lot.
apifunc() and apifunc2() translate exceptions into error codes, using the dispatcher() function.
Basically, what happens is as follows:
apifunc() (and similarly apifunc2()) attempts to call a function foo(). If foo() throws an exception, then the catch block will call dispatcher() to get the error code corresponding to the exception, and then returns that error code. If foo() doesn't throw, apifunc() returns ErrorCode_Fine indicating no error.
dispatcher() works by re-throwing the last exception thrown, i.e. the one foo() threw. dispatcher() then checks which exception was thrown using the catch blocks, and returns the correct error code. For example, if foo() threw std::bad_alloc, then that catch-block will be executed and return ErrorCode_OutOfMemory;.
Why would someone do this?
Exceptions are not necessarily binary compatible across different compilations (compilers, compiler flags, and so on), so translating exceptions to error codes is more portable across module boundaries.
When foo() throws an exception during its execution, the exception is caught in the apifunc() wrapper whose catch clause invoke the dispatcher() method. There the "current" exception is rethrown (that's the empty throw statement in the dispatcher() method) and caught again. Then the different catch clauses (bad_alloc, logic_error, myownstdexcderivedclass ... returns a sepcific error code than will be returned to the outside world.
The last catch(...) clause ensures that no exception will ever be thrown to the callers of apifunc().