I have made a class to try exceptions:
class precExcp:exception
{
public:
virtual const char* what()
{
return "Precision must be positive";
}
};
The problem is that when an exception is launched, the instructions flow doesn’t stop.
I don’t know is this is c++ default behaviour.
If yes, what to do if I want to interrupt instructions flow when an exception is caugth?
This is an example of what I do in main:
int main(int argc, char **argv)
{
try
{
if(1)
throw precExcp();
}
catch(precExcp& e)
{
cerr << e.what() <<endl;
}
cout << "hello" <<endl;
}
On the screen the “hello” string is printed, is that normal? How to avoid this?
Based on what I can understand from your question, if you want the “hello” output to be skipped, put it in the try block.
Also note that this isn’t Java or Python. C++ exception-handling generally doesn’t require you to define or catch too many different exception-types, as your main source of recovery is going to be the destructor (@see RAII) which often eliminates the need to have multiple catch branches (as well as a finally block). Often you can just catch const std::exception& (make precExcp a subclass of it) and only in some rare cases do you need more granular checking than that.
You can also rethrow:
However, if you do this in main and have no catch block to catch that second throw, it’s going to crash with an unhandled exception which may or may not be what you are seeking.