gpt4 book ai didi

c++ - 如何使用catch try catch?

转载 作者:太空宇宙 更新时间:2023-11-04 13:37:57 25 4
gpt4 key购买 nike

我的教授给了我们一个 try catch block ,他希望我们从现在开始将其用于所有代码。在阅读了它之后,我仍然对如何将它实现到我的程序中感到有点困惑。

他希望我们在程序中实现的代码。

try {
return 0;
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
keep_window_open();
return 2;
}

我正在从事的项目之一。

#include "std_lib_facilities_4a.h"
bool yes()
{
string y;
cin >> y;
if (y[0] == 'y' || y[0] == 'Y')
{
return true;
}
else
return false;
}
int main()
{
enum {question1=1, question2=2, question3=4};
int result = 0;
cout << " Is what your thinking of red?\n";
if (yes() == true)
{
result += question1;
}
cout << " Is what your thinking of round?\n";
if (yes() == true)
{
result += question2;
}
cout << " Is what your thinking of an animal?\n";
if (yes() == true)
{
result += question3;
}
vector<string> answer = {"You are thinking of a blue square!.","You are thinking of a red square!","you are thing of a blue circle!","You are thinking of a red circle!","you are thinking of a blue animal!","you are thinking of a red animal!","you are thinking of a blue round animal!","You are thinking of a red turtle!"};
cout << answer[result];
return 0;
}

最佳答案

听起来他希望您将代码放在try block 中的main 中。然后,如果程序中的任何内容抛出异常并且没有其他处理程序处理它,其中一个处理程序将捕获它并干净地结束程序。所以你的 main 看起来像

int main() try {
// your code here
return 0; // optional, but polite
} catch (exception& ex) { // better to catch a const reference
// report it
return 1; // should be EXIT_FAILURE for portability
} catch (...)
// report it
return 2; // should also be EXIT_FAILURE
}

没有它们,未捕获的异常将导致程序通过调用terminate 乱七八糟地结束。在我看来,这样更好,因为它往往更容易调试。但在短期内,按照老师说的去做可能更容易,以后再改掉所有这些坏习惯。

关于c++ - 如何使用catch try catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28891060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com