假设我们有两个正在运行的线程,它们都会抛出异常,并且这些线程中有异常处理程序。 C++ 是否能够处理这个问题,而不是遇到终止或未定义的行为。
异常属于每个线程,并且每个线程一次只能有一个异常是否正确?
最佳答案
Is it correct that exception belongs to per thread
没错。
and each thread can have no more than one exception at a time?
一个线程可以有多个事件异常。参见 int uncaught_exceptions() noexcept
:
Detects how many exceptions in the current thread have been thrown or rethrown and not yet entered their matching catch clauses.
例如:
#include <iostream>
#include <stdexcept>
void f() {
throw std::runtime_error("error");
}
struct A {
~A() {
std::cout << "uncaught_exceptions: " << std::uncaught_exceptions() << '\n';
}
};
struct B {
~B() {
try {
A a;
f();
}
catch(std::exception&) {}
}
};
int main() {
try {
B b;
f();
}
catch(std::exception&) {}
}
输出:
uncaught_exceptions: 2
关于c++ - C++中异常属于线程还是进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103950/