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:
Why does abort
get called even when I am handling string
exception?
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.
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.
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 .
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.
Quite simple really!
You threw char const*
, but do not have a matching catch
for it.
Did you mean throw std::string("...");
?
Yes, you need to be catching a char const*, not an std::string!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With