C ++ trivial try-catch causes interruption

simple code below

// g++ centro.cc -o centro #include <iostream> using namespace std; int main(int argc, char *argv[]) { try { cout << "Going to throw" << endl; throw; } catch(...) { cout << "An exception occurred" << endl; } return 0; } 

causes interruption:

 Going to throw terminate called without an active exception Aborted (core dumped) 

I don’t understand what happened, can someone point me in the right direction?

+4
source share
4 answers

Your line

 throw; 

is the syntax for throwing an exception back into the catch .

You must write:

 throw std::exception(); 
+7
source

Try something to think of. You are not making any exceptions.

throw; Itself is usually used to re-throw the same exception inside a catch .

Compare the result with throw "something"; or possibly with an instance of std::exception .

+8
source

This complies with the standard (15.1):

8). An expression without an operand repeats the current exception handling (15.3). The exception is renewed using the existing temporary; no new temporary exception object is created. The exception is no longer considered caught; therefore, the value of std :: uncaught_exception () will again be true.

9) If no exception is currently being processed, executing the throw expression without calling the operand std :: terminate () (15.5.1).

+3
source

throw; redraws the exception itself, which is currently being processed, but does not exist in your code.

You need to quit something. Instead, try something like throw std::runtime_error("my message"); . To do this, you need to include #include <stdexcept> .

In real code, you'll want to create your own exception class to throw the most likely

+2
source

All Articles