0

Assume a thread is started from the main method. What happens if an exception is thrown in the thread but not handled within the thread?Will the main thread be interrupted?

vkk
  • 19
  • 4
  • What sort of threads? – doctorlove Jul 30 '18 at 08:17
  • 3
    It depends on how you started said thread, see [this C++ reference](https://en.cppreference.com/w/cpp/thread/thread/thread#Notes). – Quentin Jul 30 '18 at 08:18
  • 1
    As is, this question is too broad. You should ask this question about a specific case. To improve this question, provide a [mcve]. – YSC Jul 30 '18 at 08:25

2 Answers2

5

What happens if an exception is thrown in the thread but not handled within the thread?

When an exception is not caught within a function executed in a std::thread, std::terminate will be called, which by default calls std::abort. This will cause the entire process to terminate unless SIGABRT signal is handled (by having registered a handler using std::signal). A minimal example:

void foo() {
    throw 0;
}

int main() {
    {
        std::thread t(foo);
        std::cout << 1 << std::endl;
    }
    std::cout << 2 << std::endl;
}

1 might be printed, depending on whether it gets to go before the process is terminated. 2 will not be printed, since the process will terminate before it is reached.

Note that while an exception can only be caught in the thread where it was thrown, it is possible to do so, copy (or move) the exception, and rethrow in the main thread where the copy can then be caught again. This approach is implemented by for example std::async. Throwing from std:::async will be caught by the standard library, and be thrown again when the returned std::future is accessed or destroyed.


If you use some threading API other than std::thread, such as the one native to your platform, consult the documentation of that API.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

A child thread runs independently from the main thread and there are various ways to communicate to child thread from the main thread. But if a child thread die and if there is any exception in a child thread there will not be any impact in main thread and a exception in a child thread can not be handle in a main thread. But if child thread generate some reports which main thread need for some operation based on that reports then it will impact that business operation in main thread.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
  • 2
    This seems to contradict the other answer, which says if there is uncaught exception in a thread, it will be significant impact on all other threads including main thread by default. – hyde Jul 30 '18 at 09:34
  • @hyde, agree but you can try with a child thread and raised an exception inside it. Main thread will run without any issue. – Abhijit Pritam Dutta Jul 30 '18 at 09:44
  • 2
    [No impact?](http://coliru.stacked-crooked.com/a/1503c6ee2db86224) – Caleth Jul 30 '18 at 10:43