c++ - C++中异常属于线程还是进程?

标签 c++ multithreading exception

假设我们有两个正在运行的线程,它们都会抛出异常,并且这些线程中有异常处理程序。 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/

相关文章:

c++ - 类(class)成员重新排序

c++ - 基于基类方法的生成类中的运算符重载

java - C、C++ 和 Java 中的不同结果相同的表达式。为什么?

c# - 既然有SpinWait,为什么还要使用SpinLock呢?

c# - Sitecore 项目的错误处理

python - 一旦遇到异常,我可以忽略下面的所有行并转到 for 循环中的另一个项目吗?

C# 异常处理与方法结果返回错误

c++ - MPI_Isend/Recv-是否存在死锁?

windows - 搁置线程是最优的吗?

c# - 使用 Dispatcher.Invoke/BeginInvoke 本质上是否提供对一段代码的互斥访问?