以下 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/