try\catch main() 函数中没有括号的块

try\catch block in the main() function without brackets

Visual Studio 2015 年; C++语言。

我记得我在某处读到有关入口点(即 main 方法)的内容:

#include <iostream>
using namespace std;

int main()
try{
  return 0; // I am here...
}
catch (...){
  cout << "I am 'catch'..." << endl; // This row wasn't called!
  return 1; // Oops... But the next `F10` key pressing jumps from the "try" 
  // block into this row!
}

即在这种情况下,try\catch 块不在括号中:

int main() { // start bracket
  try{
    return 0;
  }
  catch (...){
    return 1;
  }
} // end bracket

两种情况都已成功编译并且也可以正常工作,但是......在第一个变体中,当我在 try 块之后逐步按下 F10 键时,我进入 catch挡也。对于第二种代码变体,我没有这种行为。

为什么会这样?

C++ 规范指出:

A function-try-block associates a handler-seq with the ctor-initializer, if present, and the compound-statement. An exception thrown during the execution of the compound-statement or, for constructors and destructors, during the initialization or destruction, respectively, of the class’s subobjects, transfers control to a handler in a function-try-block in the same way as an exception thrown during the execution of a try-block transfers control to other handlers.

构造函数或任何其他函数中的函数 try 块的 usage/behaviour 没有特殊用例。

您的构造是一个 function-try-block 并在 drafs n4296 中针对 C++ 11 规范在 8.4 函数定义 [dcl.fct.def.general] 中定义:

Function definitions have the form

  • function-definition:
    • attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt function-body
  • function-body:
    • ctor-initializeropt compound-statement
    • function-try-block
    • = default ;
    • = delete ;

及之后的 15 异常处理 [except] with:

function-try-block:

  • try ctor-initializeropt compound-statement handler-seq

示例表明函数 try 块的正常用法应该是 ctor,但它对普通函数有效(并且 main 在语法上只是一个函数)

有效并正常工作,这意味着只有在复合语句中的 ctor-initializeropt on 发生异常时才会评估 catch 块。您可以通过在块中添加打印或测试 return 值来在代码中确认它。

在类 Unix 系统中

foo
echo $?

应该回显0

在 Windows 系统中 CMD.exe windows

foo.exe
if errorlevel 1 echo "Catch block"

不应该输出Catch block

如果您的调试器允许您在 catch 块中执行 指令...它不符合 C++ 11!

但众所周知,当退出一个块时,MSVC 调试器将光标放在块的最后一行,我假设这就是这里发生的事情,因为函数尝试块的最后一行 catch 的最后一行。