I've the following piece of code
try
{
// Vector creation in shared memory. The shm must exist.
m_pxShm = new managed_shared_memory(open_only, pcShmName);
m_pxShm->construct<T>(pcVecName)[iSize](); // THROW EXCEPTION <==
m_xVectorPair = m_pxShm->find<T>(pcVecName);
if (0 == m_xVectorPair.first)
{
throw std::exception();
}
}
catch (std::exception)
{
throw SharedMemoryVectorBadAllocException();
}
The SharedMemoryVectorBadAllocException use std::exception as base class. When I run this piece of code, the line with the 'construct' method throws an exception (because I create a vector bigger than shared memory). But the thrown exception is not handled, and the application crashes. Even if I debug it, line by line, the exception is not handled by the catch statement. I've tried to use as catch argument std::exception, interprocess_exception, ... and so on, without success. How can I handle the exception ? I'm using Visual studio 2010.
Related
In C++ reference regarding the set_exception method , the example uses std::current_exception. To do that you have to throw and catch your exception:
std::thread t([&p]{
try {
// code that may throw
throw std::runtime_error("Example");
} catch(...) {
try {
// store anything thrown in the promise
p.set_exception(std::current_exception());
// or throw a custom exception instead
// p.set_exception(std::make_exception_ptr(MyException("mine")));
} catch(...) {} // set_exception() may throw too
}
});
This throwing and catching is obviously tedious, but the method accepts a std::exception_ptr. I was wondering whether it's possible to set a specific exception directly. I imagine the problem would be that a local exception object would have lifetime issues if we pass around a pointer to its address and allocating a new exception object would leave memory leaks. Is there a way ?
Currently, I am investigating some code that uses the CFile class from the MFC Library to open a text file.
I found two kinds of error handling in the code: This are just sample since it is confidential to post the code.. Just think that the body of the try statement contains only member functions of CFile class.
1
try {
if(file.Open(strPath,Cfile::modeRead|CFile::shareDenyNone)){
file.Read(strKey, dataLength);
file.Close();
}
}
catch (CFileException& e) {
}
2
try {
// same code above
}
catch (CFileException *e) {
}
What is the difference between the two kinds of exception handling?
What are the possible errors that can be thrown by member functions of the CFile class?
Is no. 1 way possible for catching exceptions thrown by a member function of the CFile class?
You can throw exception objects in two ways, by value:
CException ex;
throw ex; // CException
or by pointer:
CException *ex = new CException();
throw ex; // CException *
When catching the exception, you catch the corresponding type of what has been thrown, that is, a pointer, or a value. To avoid a copy, we usually catch-by-value using a reference:
catch(CException &e) // when throwing CException
MFC throws exceptions by pointer; see https://msdn.microsoft.com/en-us/library/0e5twxsh.aspx
try {
AfxThrowUserException();
}
catch( CException* e ) {
e->Delete();
}
Don't forget do delete the exception afterwards, or you get a small memory leak each time an exception is thrown.
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)"
I did bit of researching while trying to find proper way to implement exceptions in my code I came accross
Throw by value, catch by reference
to be the recommended way of deal exceptions in C++ . I have a confusion about when the exception thrown gets out of scope.
I have following exception hierarchy
ConnectionEx is mother of all connection exceptions thrown by dataSender
ConnectionLostEx is one of the subclasses of ConnectionEx
so here is a sample code. In words DataSender instance is member of DataDistrubutor who calls functions on dataSender for example send() and DataSender throws ConnectionEx's subclasses as exceptions in case of problems.
// dataSender send() function code chunk
try
{
// some problem occured
// create exception on stack and throw
ConnectionLostEx ex("Connection lost low signals", 102);
throw ex;
}
catch(ConnectionLostEx& e)
{
//release resources and propogate it up
throw ;
}
//A data distributor class that calls dataSender functions
try
{
// connect and send data
dataSender.send();
}
catch(ConnectionEx& ex)
{
// free resources
// Is the exception not out of scope here because it was created on stack of orginal block?
//propogate it further up to shows cause etc..
}
In C# or java we have a pointer like reference and that it valid all the way up, I am confused about the scope of exceptions given the exception is thrown by value when exactly does it get out of scope ??? and when caught as parent type ConnectionEx in this case can this be casted to get the real one back somwhere up in the chain of catch blocks ??
A copy of the exception is thrown, not the original object. There's no need to instantiate a local variable and throw it; the idiomatic way to throw an exception is to instantiate it and throw it on the same line.
throw ConnectionLostEx("Connection lost low signals", 102);
I am new to programming and am having trouble with try / catch clauses.
Here is an example from a textbook that I have:
int main( )
{
char *ptr;
try {
ptr = new char[ 1000000000 ];
}
catch( … ) {
cout << "Too many elements" << endl;
}
return 0;
}
I have tried to look online for a further explanation and the textbook does not exactly tell me what what these clauses actually do or what it is used for.
Any information would be helpful.
EDIT: The textbook I am using is:
C++: Classes and Data Structures by Jeffrey Childs
A try-catch is the C++ construct for exception handling. Google 'C++ exceptions'.
Try catch is a way of handling exceptions:
try
{
// Do work in here
// If any exceptions are generated then the code in here is stopped.
// and a jump is made to the catch block.
// to see if the exception can be handled.
// An exception is generated when somebody uses throw.
// Either you or one of the functions you call.
// In your case new can throw std::bad_alloc
// Which is derived from std::runtime_error which is derived from std::exception
}
// CATCH BLOCK HERE.
The catch block is where you define what exceptions you want to handle.
// CATCH BLOCK
catch(MyException const& e)
{
// Correct a MyException
}
catch(std::exception const& e)
{
// Correct a std::exception
// For example this would cat any exception derived from std::exception
}
You can have as many catch blocks as you like. If you exception matches any of the catch expressions in the catch statement then the associated block of code is executed. If no catch expressions matches an exception then the stack is unwound until it finds a higher level catch block and the processes is repeated (this can cause the application to exit if no matching catch block is found).
Note: If multiple catch expressions match then the lexically first one is used. Only one or none of the catch blocks will be executed. If none then the compiler will look for a higher level try/catch.
There is also a catch anything clause
catch(...)
{
// This is a catch all.
// If the exception is not listed above this will catch any exception.
}
So how does this apply to your code.
int main( )
{
char *ptr;
try
{
// This calls ::new() which can potentially throw std::bad_alloc
// If this happens then it will look for a catch block.
ptr = new char[ 1000000000 ];
// If the ::new() works then nothing happens and you pointer `ptr`
// is valid and code continues to execute.
}
catch( … )
{
// You only have one catch block that catches everything.
// So if there are any statements that generate an exception this will catch
// the excetption and execute this code.
cout << "Too many elements" << endl;
}
// As you have caught all exceptions the code will continue from here.
// Either after the try block finishes successfully or
// After an exception has been handled by the catch block.
return 0;
}
Try-catch blocks are used to trap errors in the code.
At the most basic level, errors occur because the program tries to execute an invalid instruction. That instruction (read: line of code) could be invalid for a number of reasons. In your specific instance, the instruction could be invalid if your program was not able to allocate 1,000,000,000 bytes of memory to story your ptr. The most common exception is trying to access a bad pointer, which is called a Null Pointer Exception, which occurs when you try to perform some action on an Object that either has not been created, or has been deleted (or got corrupt). You will learn to hate that exception.
Using catch(...) tells the program to execute the code inside the catch block if any error occurs inside the code within the try block. There you can handle your error and try to find someway to either fix the error condition or gracefully exit that module.
You can also catch specific errors, which you can find out more about here : http://www.cplusplus.com/doc/tutorial/exceptions/
If you already know C, try/catch achieves the same thing as setjmp/longjmp when used for error handling. Think of try as code for the if condition of setjmp and catch code for else of setjmp. This makes longjmp equivalent to throw in C++, which is used to throw an exception. In your example, probably, the new operator, which calls some memory allocation function internally, throws an exception on seeing a very large number as input by using the C++ throw operator.
void a()
{
.......
longjmp(buf,1); // <--- similar to throw
.......
}
if ( !setjmp(buf) ) // <--- similar to try
{
.......
a();
.......
}
else // <--- similar to catch
{
.......
}
try/catch is a bit more sophisticated than setjmp/longjmp, as for setjmp/longjmp you will need to declare variables which are modified in between setjmp/longjmp calls as volatile, which is not necessary for try/catch.