Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is abort method called?

Tags:

c++

exception

In the following program abort method is called even when I have got the applicable catch statement. What is the reason?

#include <iostream>
#include <string>
using namespace std;

int main() {

    try {
        cout << "inside try\n";
        throw "Text";
    }
    catch (string x) {
        cout << "in catch" << x << endl;
    }

    cout << "Done with try-catch\n";
}

When I run the program I only get the first statement inside try displayed and then I get this error:

enter image description here

Why does abort get called even when I am handling string exception?

like image 392
Suhail Gupta Avatar asked Jul 01 '11 13:07

Suhail Gupta


People also ask

What is Abort method?

Abort() This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Generally, this method is used to terminate the thread.

What will happen if the abort method is called on a thread?

If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur. If Abort is called on a thread that has not been started, the thread will abort when Start is called. If Abort is called on a thread that is blocked or is sleeping, the thread is interrupted and then aborted.

Why is thread abort obsolete?

Abort may prevent the execution of static constructors or the release of managed or unmanaged resources. For this reason, Thread. Abort always throws a PlatformNotSupportedException on .

What is ThreadAbortException?

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.


3 Answers

Quite simple really!

You threw char const*, but do not have a matching catch for it.

Did you mean throw std::string("...");?

like image 136
Lightness Races in Orbit Avatar answered Sep 20 '22 12:09

Lightness Races in Orbit


Yes, you need to be catching a char const*, not an std::string!

like image 42
MGZero Avatar answered Sep 19 '22 12:09

MGZero


Apart from what the other answers tell, as a general advice: Only throw what is derived from std::exception, and if nothing else, in your top-handler, catch std::exception& or const std::exception&. This would have e.g. avoided this situation. See also

  • C++ FAQ 17.2: What should I throw
  • C++ FAQ 17.3: What should I catch
like image 24
Sebastian Mach Avatar answered Sep 19 '22 12:09

Sebastian Mach