C++ uncaught exception in worker thread - c++

Uncaught exception behaves differently for main thread and another std::thread.
here is the test program
#include <thread>
class XXX{
public:
XXX(){std::fprintf(stderr, "XXX ctor\n");}
~XXX(){std::fprintf(stderr, "XXX dtor\n");}
};
void mytest(int i)
{
XXX xtemp;
throw std::runtime_error("Hello, world!");
}
int main(int argc, char *argv[])
{
if(argc == 1) {
mytest(0);
}else{
std::thread th([&]{mytest(0);});
th.join();
}
}
above code (C++11), compiled by GCC 5.4
run without args
XXX ctor
terminate called after throwing an instance of 'std::runtime_error'
what(): Hello, world!
Aborted (core dumped)
run 1 arg:
XXX ctor
XXX dtor
terminate called after throwing an instance of 'std::runtime_error'
what(): Hello, world!
Aborted (core dumped)
So the stack unwind is performed in worker thread but not in main thread, WHY?
I'm asking because I'd like core dump to give useful stack backtrace information in both cases (for uncaught exception).
Thanks in advance!!!
Further trials reveals that add noexcept keyword to thread function body mytest() can partially solves my problem because unwind will fail,but its not a good solution because unwind will still partially happen if mytest() is calling another function without noexcept guarantee and actually thrown the uncaught exception.
Update: Thanks to all comment providers, now I understand C++ exception is not backtrace friendly, and GCC, as a C++ implementation,has the freedom to choose to not unwind when uncaught exception is thrown from main thread, and unwind when from worker thread.
Update: Special thanks to Sid S & Jive Dadson, I must mixed up some concepts: 1) exception/error handling; 2) runtime assertion 3) Segment fault, 2&3 are similar, they are UN-recoverable errors, abort immediately is the only choice, they are also backtrace friendly in debugger because stack unwind is not involved. they should not be implemented using exception concept at all. exception is supposed to be caught always, let uncaught exception leaving main() is not a recommended usage.

Why? That's just the way it is. Since c++11, there is some support for dealing with exceptions thrown in threads other than main, but you will need to instrument the threads to catch exceptions and re-throw them. Here's how.
#include <thread>
#include <iostream>
class XXX {
public:
XXX() { std::fprintf(stderr, "XXX ctor\n"); }
~XXX() { std::fprintf(stderr, "XXX dtor\n"); }
};
void mytest(int i)
{
XXX xtemp;
throw std::runtime_error("Hello, world!");
}
int main(int argc, char *argv[])
{
std::exception_ptr exception_ptr = nullptr;
if (argc == 1) {
mytest(0);
}
else {
std::thread th([&exception_ptr]() {
try {
mytest(0);
}
catch (...) {
exception_ptr = std::current_exception();
}
});
th.join();
if (exception_ptr) {
try {
std::rethrow_exception(exception_ptr);
}
catch (const std::exception &ex)
{
std::cerr << "Thread exited with exception: " << ex.what() << "\n";
}
}
}
}

You should catch the exception in the thread where it occurs. The default handler will call terminate() wherever it is at, unwinding or not depending on implementation.

Related

Throwing an exception when another exception has not been handled yet. (C++)

As far as I know, throwing an exception when another has not been handled yet is undefined behavior, and the program may crash. An exception is considered unhandled until it gets into the catch-block. I have the following code snippet:
#include <iostream>
using namespace std;
class ThrowingInDestructorClass
{
public:
ThrowingInDestructorClass() = default;
~ThrowingInDestructorClass() {
try {
throw std::runtime_error("2-nd exception. ");
}
catch(...)
{
std::cout << "Catched an error during Throwing class cleanup. " << std::endl;
};
}
};
void doSmth()
{
try {
ThrowingInDestructorClass throwing;
throw std::runtime_error("1-St exception. ");
}
catch(...)
{
std::cout << "Catched an error during doSmth. " << std::endl;
};
}
int main() {
doSmth();
}
Here we have a class that can throw and handle an exception inside its destructor, so it is OK. But we have a method that creates objects and throws an exception. During stack-unwinding, the class destructor will be called, throwing a 2-nd exception. So the 1-St exception will be unhandled yet.
When I run it, I get the following output:
Caught an error during Throwing class cleanup.
Caught an error during doSmth.
It may seem that everything is fine, but I'm not entirely sure that there is no UB here.
Could someone help to clarify the situation?
This answer is mostly just a summary of the comments:
I'll go through the program step by step starting at the point the first exception is thrown:
Stack unwinding begins by destroying the "throwing" object.
The destructor of the "throwing" object gets called, throwing another exception.
Stack unwinding finds a catch block for the new exception immediately, handling the exception. The destructor exits normally.
The stack unwinding finds the catch block for the first exception, handling it.
doSmth() exits normally
No function exited with an exception, thereby the condition
"...If any function that is called directly by the stack unwinding mechanism, after initialization of the exception object and before the start of the exception handler, exits with an exception, std::terminate is called. ..." en.cppreference.com/w/cpp/language/throw - Richard Critten
isn't met.
And even if you remove the try catch in the destructor, no UB will occur:
#include <iostream>
using namespace std;
class ThrowingInDestructorClass
{
public:
ThrowingInDestructorClass() = default;
~ThrowingInDestructorClass() {
throw std::runtime_error("2-nd exception. ");
}
};
void doSmth()
{
try {
ThrowingInDestructorClass throwing;
throw std::runtime_error("1-St exception. ");
}
catch(...)
{
std::cout << "Catched an error during doSmth. " << std::endl;
};
}
int main() {
doSmth();
}
This program will crash because std::terminate is called when stack unwinding (as now a function exits with an exception).
If you throw an exception when another has not been handled yet, and you let the second exception escape a destructor that was called in process of handling the first exception, then you get a well-defined program termination. –
n. 1.8e9-where's-my-share m.
Your program will crash, but that crash is not UB but well-defined behaviour

Exception not caught after signal

I try to catch a termination signal to my code to write a restart file before exiting. My solution is based on this answer.
#include <exception>
#include <csignal>
#include <iostream>
class InterruptException : public std::exception
{
public:
InterruptException(int _s) : signal_(_s) { }
int signal() const noexcept
{
return this->signal_;
}
private:
int signal_;
};
/// method to throw exception at signal interrupt
void sig_to_exception(int s)
{
throw InterruptException(s);
}
int main()
{
// activate signal handling
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = sig_to_exception;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
try
{
for (std::size_t i = 0; i < 100000000; ++i)
{
std::cout << i << std::endl;
}
}
catch (const InterruptException& e)
{
std::cout << "Received signal " << e.signal() << std::endl;
std::exit(1);
}
catch(...)
{
std::cout << "Other catch!" << std::endl;
}
}
The exception gets thrown fine, however, my catch block does not catch it. The program terminates with an uncaught exception InterruptException. I tried with clang and gcc on MacOS. Any idea why the exception is not caught correctly?
Thanks
Output when compiled with g++ 7.3.0:
terminate called after throwing an instance of 'InterruptException'
what(): std::exception
Abort trap: 6
Output when compiled with Apple LLVM 9.0.0
libc++abi.dylib: terminating with uncaught exception of type InterruptException: std::exception
PS: It seems when I compile with Apple LLVM the exception gets caught sometimes, but not all the time, which makes this even weirder.
There is very little that you can reliably do in a signal handler. In particular, you cannot throw an exception. The code in the question (and the "answer" that it links to) relies, at best, on compiler/OS-specific behavior. For the limits on what you can do in a signal handler, see this.
Note that the link above refers to signal, which is standard C. sigaction is not standard C, it's POSIX, and the C++ language definition doesn't impose any requirements on a program that uses it.
On most system the stack frame used by the signal handler is not a standard function stack frame as defined by the compiler for function calls.
So throwing out of a sig handler is not supported.
Stack frame for signal handling in the Linux Kernel
From the discussion in the linked question, on a linux system they are not even using the same stack for the stack frame and returning requires jumping back to a system function to restore the original user stack.
Unless the OS is specifically designed to handle exceptions then this is not going to work.
The rule of thumb for signal handlers is to do as little as possible in a signal handler. Set a global flag that can be detected by your normal code then check that flag periodically in your normal code to see when the signal has happened.

concurrency::task destructor causes call to abort in valid use-case

Could you please tell me if the approach I use to handle the use-case is invalid and if so, what is the right way to handle:
task<int> do_work(int param)
{
// runs some work on a separate thread, returns task with result or throws exception on failure
}
void foo()
{
try
{
auto result_1 = do_work(10000);
auto result_2 = do_work(20000);
// do some extra work
process(result_1.get(), result_2.get());
}
catch (...)
{
// logs the failure details
}
}
So the code tries to execute two jobs in parallel and then process the results. If one of the jobs throws an exception, then call task::get will re-throw the exception. The issue happens if both tasks throw an exception. In this case the first call to task::get will cause stack unwind, so the destructor of the second task will be called and will in turn cause one more exception to be re-thrown during stack unwind which causes 'abort' to be called.
This approach seemed completely valid to me until I faced with the issue.
In simple words you have an un-handled (unobserved) exception as the exception thrown in one of your tasks does not get caught by the task, one of its continuations, or the main app, because the exception re-thrown from task::get for the first task unwinds the stack before the call to task::get happens for the second task.
A more simplified code shows that std::terminate is called because the exception thrown in the task does not get handled. Uncommenting the result.get() will prevent the call to std::terminate, as task::get will re-throw the exception.
#include <pplx/pplx.h>
#include <pplx/pplxtasks.h>
#include <iostream>
int main(int argc, char* argv[])
{
try
{
auto result = pplx::create_task([] ()-> int
{
throw std::exception("task failed");
});
// actually need wait here till the exception is thrown, e.g.
// result.wait(), but this will re-throw the exception making this a valid use-case
std::cout << &result << std::endl; // use it
//std::cout << result.get() << std::endl;
}
catch (std::exception const& ex)
{
std::cout << ex.what() << std::endl;
}
return 0;
}
have a look at the suggestion in pplx::details::_ExceptionHandler::~_ExceptionHolder()
//pplxwin.h
#define _REPORT_PPLTASK_UNOBSERVED_EXCEPTION() do { \
__debugbreak(); \
std::terminate(); \
} while(false)
//pplxtasks.h
pplx::details::_ExceptionHandler::~_ExceptionHolder()
{
if (_M_exceptionObserved == 0)
{
// If you are trapped here, it means an exception thrown in task chain didn't get handled.
// Please add task-based continuation to handle all exceptions coming from tasks.
// this->_M_stackTrace keeps the creation callstack of the task generates this exception.
_REPORT_PPLTASK_UNOBSERVED_EXCEPTION();
}
}
In the original code the first call to task::get raises the exception thrown in that task, which obviously prevents the second call to task::get so the exception of the second task does not get handled (remains "unobserved").
the destructor of the second task will be called and will in turn cause one more exception to be re-thrown during stack unwind which causes 'abort' to be called.
The destructor of the second task does not re-throw the exception it just calls std::terminate() (which calls std::abort())
see. Exception Handling in the Concurrency Runtime

How to throw with some printout in C++

If I just simply use throw some_string; then I get terminate called after throwing an instance of 'std::string'. How can I get some printout with the string value actually shown, for example, terminate called after throwing 'This is wrong', or something similar?
Thank you.
Generally, you should be throwing subclasses of std::exception. Most C++ implementations automatically print out the result of calling exception::what() if the exception is uncaught.
#include <stdexcept>
int main()
{
throw std::runtime_error("This is wrong");
}
With GCC, this outputs:
terminate called after throwing an instance of 'std::runtime_error'
what(): This is wrong
Aborted
You have to add code somewhere to deal with the thrown object. If you do nothing the program ends in calling abort and the result of that is implementation defined. The solution for you is to add a catch block somewhere in your code, for example in your main function. Here's why
You can catch the object you threw and construct a meaningful error message.
The default behavior results in terminating the program immediately without unwinding the stack and cleaning up. The object that is throw must be caught somewhere before main returns in order to avoid this.
You have to catch the exception
#include <iostream>
#include <string>
int main(int argc, char *argv[]) try
{
throw std::string("This is a test");
return 0;
}
catch(const std::string &s)
{
std::cout << s << std::endl;
}

why does throw "nothing" causes program termination?

const int MIN_NUMBER = 4;
class Temp
{
public:
Temp(int x) : X(x)
{
}
bool getX() const
{
try
{
if( X < MIN_NUMBER)
{
//By mistake throwing any specific exception was missed out
//Program terminated here
throw ;
}
}
catch (bool bTemp)
{
cout<<"catch(bool) exception";
}
catch(...)
{
cout<<"catch... exception";
}
return X;
}
private:
int X;
};
int main(int argc, char* argv[])
{
Temp *pTemp = NULL;
try
{
pTemp = new Temp(3);
int nX = pTemp->getX();
delete pTemp;
}
catch(...)
{
cout<<"cought exception";
}
cout<<"success";
return 0;
}
In above code, throw false was intended in getX() method but due to a human error(!) false was missed out. The innocent looking code crashed the application.
My question is why does program gets terminated when we throw "nothing”?
I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
This is expected behaviour. From the C++ standard:
If no exception is presently being
handled, executing a throw-expression
with no operand calls
terminate()(15.5.1).
As to why the compiler can't diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would not judge it as cost-effective. C++ (and other languages) are full of possible errors that could in theory be caught by the compiler but in practice are not.
To elaborate on Neil's answer:
throw; by itself will attempt to re-raise the current exception being unwind -- if multiple are being unwound, it attempts to rethrow the most recent one. If none are being unwound, then terminate() is called to signal your program did something bogus.
As to your next question, why the compiler doesn't warn with throw; outside a catch block, is that the compiler can't tell at compile-time whether the throw; line may be executing in the context of a catch block. Consider:
// you can try executing this code on [http://codepad.org/pZv9VgiX][1]
#include <iostream>
using namespace std;
void f() {
throw 1;
}
void g() {
// will look at int and char exceptions
try {
throw;
} catch (int xyz){
cout << "caught int " << xyz << "\n";
} catch (char xyz){
cout << "caught char " << xyz << "\n";
}
}
void h() {
try {
f();
} catch (...) {
// use g as a common exception filter
g();
}
}
int main(){
try {
h();
} catch (...) {
cout << "some other exception.\n";
}
}
In this program, g() operates as an exception filter, and can be used from h() and any other function that could use this exception handling behavior. You can even imagine more complicated cases:
void attempt_recovery() {
try{
// do stuff
return;
} catch (...) {}
// throw original exception cause
throw;
}
void do_something() {
for(;;) {
try {
// do stuff
} catch (...) {
attempt_recovery();
}
}
}
Here, if an exception occurs in do_something, the recovery code will be invoked. If that recovery code succeeds, the original exception is forgotten and the task is re-attempted. If the recovery code fails, that failure is ignored and the previous failure is re-throw. This works because the throw; in attempt_recovery is invoked in the context of do_something's catch block.
From the C++ standard:
15.1 Throwing an exception
...
If no exception is presently being
handled, executing a throw-exception
with no operand calls terminate()
The reason the compiler can't reliably catch this type of error is that exception handlers can call functions/methods, so there's no way for the compiler to know whether the throw is occurring inside a catch. That's essentially a runtime thing.
I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
Rethrowing is useful. Suppose you have a call stack three levels deep with each level adding some context resource object for the final call. Now, when you have an exception at the leaf level, you will expect some cleanup operation for whatever resources the object has created. But this is not all, the callers above the leaf may also have allocated some resources which will need to be deallocated. How do you do that? You rethrow.
However, what you have is not rethrow. It is a signal of giving up after some failed attempts to catch and process any and all exceptions that were raised.
A throw inside of a catch block with no args will re-throw the same exception that was caught, so it will be caught at a higher level.
A throw outside of a catch block with no args will cause a program termination.
To complete the previous answers with an example of when/why the compiler cannot detect the problem:
// Centralized exception processing (if it makes sense)
void processException()
{
try {
throw;
}
catch ( std::exception const & e )
{
std::cout << "Caught std::exception: " << e.what() << std::endl;
}
catch ( ... )
{
std::cout << "Caught unknown exception" << std::endl;
}
}
int main()
{
try
{
throw 1;
}
catch (...)
{
processException(); // correct, still in the catch clause
}
processException(); // terminate() no alive exception at the time of throw.
}
When compiling the function processException the compiler cannot know how and when it will be called.
You don't have anything to catch, and so the exception bubbles all the way up. Even catch(...) needs something.