I want to throw an exception like this:
if (...) {
throw "not found";
}
and catch it like this:
try {
myfunction();
} catch (const char * msg) {
cout << msg << endl;
}
but then it says
terminate called after throwing an instance of 'char const*'
Why does it call terminate and not throw my "not found"?
EDIT:
I changed it to this:
try {
throw "not found";
} catch (const char * msg) {
cout << "test" << endl;
} catch(...) {
cout << "test" << endl;
}
and I get the same error!
EDIT2: When I don't call a specific method above, it works! But I don't understand what this method has to do with exceptions, I didn't use it in any other function than the above mentioned myfunction(). Let me test some more and then I will get back to you!
EDIT3:
Oh my, this is embarrassing. Looks like I called the wrong function. I am so so sorry to have bothered you with this shameful experience!
If you use throw outside of a try/catch block, terminate gets called. Make sure the function that throws is in the try block.
#include <iostream>
void myFunc()
{
throw "Throwing!";
}
int main()
{
try
{
myFunc();
}
catch(...)
{
std::cout << "Works fine.";
}
myFunc(); // Terminate gets called.
return 0;
}