关于错误处理的 main() 末尾的 C++ 错误

C++ Error at end of the main() regarding Error Handling

void main(){
    try {
        GameEntry deletedItem = newList.remove(13);
    }
    catch (IndexOutOfBound &e) {
        cout << e.what() << endl;
    }
    cout << ":)";
}

在此源代码中,在 catch() 的错误处理后,主函数成功放入“:)”,但在 main() 函数的末尾发生未知错误。 我知道如何通过在 cout << ":)" 之后放置 exit(0) 来修复此错误,但我不知道原因。 returnexit 在错误处理方面有什么区别吗?当我使用 try catch 块时,我是否必须使用 int main(),而不是 void main()

[已解决] 我发现 class.

的析构函数有错误

处理这个错误与main的return类型无关。它应该总是 int main().

returnexit()的区别:

  • return 为您的作用域变量调用析构函数
  • exit() 除静态变量外没有调用析构函数

所以你应该小心使用exit()

I know that how to fix this error by putting exit(0) after cout << ":)"

这不能修复错误。
错误只是被隐藏了,因为导致错误的代码不是 运行.

当您调用 exit() 时,它不会 return 从调用。这意味着堆栈没有展开,因此本地对象没有被销毁。这表明您的某个本地对象的析构函数存在错误。

很遗憾,您没有显示任何对象,因此很难告诉您错误是什么。

void main(){

    // You have some variables declared here.
    // That get destroyed when main() exists (ie there destructors run).
    // This is where you bug is.
    // calling exit() after the last line below will hide this error
    // as the destructor for these objects will not be run.

    try {
        GameEntry deletedItem = newList.remove(13);
    }
    catch (IndexOutOfBound &e) {
        cout << e.what() << endl;
    }
    cout << ":)";
}

return和退出Error-handling有区别吗?

唯一的主要区别是自动变量不会被销毁(因为退出不会 return 因此堆栈不会展开)。其他都一样。

Do I have to use int main(), not void main() when I use try catch block?

使用 void main() 无效。

程序的唯一有效版本具有如下声明的主程序:

int main()

int main(int argc, char* argv[])  // or equivalent types.

任何其他声明都是非标准的(尽管允许)。

备注:

6.8.3.1 main function
1: A program shall contain a global function called main. Executing a program starts a main thread of execution in which the main function is invoked, and in which variables of static storage duration might be initialized and destroyed. It is implementation-defined whether a program in a freestanding environment is required to define a main function.
2: An implementation shall not predefine the main function. This function shall not be overloaded. Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined. An implementation shall allow both

— a function of () returning int and

— a function of (int, pointer to pointer to char) returning int

3: The function main shall not be used within a program. The linkage of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed. The main function shall not be declared with a linkage-specification. A program that declares a variable main at global scope or that declares the name main with C language linkage (in any namespace) is ill-formed. The name main is not otherwise reserved.