c++ - 最后一个关联处理程序之后的变量

标签 c++ function try-catch

以下 3.3.3/2 引用:

If the function has a function-try-block the potential scope of a parameter or of a function-local predefined variable ends at the end of the last associated handler, otherwise it ends at the end of the outermost block of the function definition.

考虑以下示例:

void foo()
{
    int a; //function-local predefined variable
    std::cin >> a;
    int z;
    try
    {
        z=5/a;
        std::cout << z << "\n";

    }
    catch(std::logic_error e)
    {
        std::cout << "Division by zero";
    } //end of the last associated handler
    std::cout << a; //a is still visible
}

为什么 a 在最后一个关联的处理程序之后仍然可见?

最佳答案

函数 try block 如下所示:

void f()
try
{
    // Some code that might throw
}
catch(std::exception& e)
{
    // Exception caught
}

你拥有的是一个普通的函数,里面有一个普通的 try-catch block 。

当像这样定义函数时,很明显函数中声明的变量(即在 try block 中声明的变量)不会存在于 try 之外。 block 。

关于c++ - 最后一个关联处理程序之后的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23731821/

相关文章:

c++ - 获取 OpenGL 纹理中特定像素的颜色?

ios - 我可以在 swift 中有两种类型的参数吗?

c++ - 如何安全地处理容器类中的异常/异常?

arrays - 警告 : A long-running operation is being executed on the main thread. 尝试一下!获取数据()。 swift

c++ - 添加长年持续时间的 Boost.DateTime 问题

c++ - 如何将 ""替换为 "_"?

列中的 SQL 函数运行缓慢

c - 运行程序时出错 "Segmentation fault core dumped"

C# - 围绕抛出自定义异常或处理案例构建逻辑更好吗?

c++ - Linux 上的编译器 (GCC) 交叉编译(到 Windows)——如何在非源目录中构建它?