c++ - throw 和捕捉整数是如何工作的?

标签 c++ exception try-catch

使用此代码:

int main()
{
    try
    {
        throw -1;
    }
    catch (int& x)
    {
        std::cerr << "We caught an int exception with value: " << x << std::endl;
    }
    std::cout << "Continuing on our merry way." << std::endl;

    return 0;
}

我们有:
/tmp$ ./prorgam.out
Continuing on our merry way
We caught an int exception with value: -1
catch怎么办块读取-1int& ?我们无法为非常量左值引用赋值。

为什么是第二个 std::cout在第一个 std::cerr 之前执行的语句陈述?

最佳答案

这没关系,因为 [except.throw]/3

Throwing an exception copy-initializes ([dcl.init], [class.copy.ctor]) a temporary object, called the exception object. An lvalue denoting the temporary is used to initialize the variable declared in the matching handler ([except.handle]).



强调我的

如您所见,即使它是临时的,编译器也将其视为用于初始化处理程序的左值。因此,您不需要 const 引用。

关于c++ - throw 和捕捉整数是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412118/

相关文章:

c++ - 从 std::cin 读取密码

c++ - 在 C++ 中将类变量传递给异常

c++ - 将 char32_t 打印到控制台

java - Android 未处理的异常错误

c# - 正确处理两个 WebException

java - 在 catch block 中抛出异常需要另一个 try catch block

olSync 服务器上的 PowerShell tr​​y/catch 语句

c++ - 为什么我的线程计数器并不总是完成?

java - 如何遵循 IntelliJ-IDEA 关于 try/catch block 的建议 "catch branch identical"?

android - AlertDialog 未显示在 catch block 中