如何使用catch try-catch
How to use a catch try catch?
我的教授给了我们一个try-catch块,他希望我们从现在起将其用于所有代码。在阅读了它之后,我仍然有点困惑于如何将它实现到我的程序中。
他希望我们在程序中实现的代码。
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;
}
听起来他想让你把main
中的代码放在try
块中。然后,如果程序中有任何东西抛出异常,而没有其他东西处理它,那么其中一个处理程序将捕获它并干净地结束程序。所以你的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
而混乱地结束。在我看来,这更好,因为它往往更容易调试。但在短期内,按照老师的话做,以后再改掉所有这些坏习惯可能会更容易。
相关文章:
- 编译器是否必须始终删除 try-catch 块(如果它被证明是非抛出的)
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 在大型应用程序的main上使用try-catch
- RapidXML 节点在 try catch 块中具有正确的值,但它在块外为 nullptr
- 提取 try-catch 时出现运行时错误
- std::unique_ptr 在 try-catch 块中未捕获取消引用异常
- 何时删除 try-catch 块中的指针
- 是否有理由大多数/所有 try-catch 示例只对 throw 语句使用 void 子函数
- 如何使用 try 和 catch 中止函数
- 使用 VC++ 中的 Try 和 catch 块捕获内存访问冲突
- 如何在这个try-show-catch代码中对异常进行排序
- 是否可以在不同的类中编写/包装异常处理组件(try、catch)
- c++ catch catch bad_alloc and delete pointer
- map/unordered_map:首选find(),然后at()或try at() catch out_of_rang
- C++: "try { foo(); } catch (...) { throw; }"可以优化以"foo();"吗?
- 测试"Try and Catch"
- 在c++中使用try和catch方法创建一个函数来获取用户名
- 为什么在C++中使用try-and-catch()
- try和catch块没有捕获异常,而是将结果作为无穷大