【问题标题】:How to use a catch try catch?如何使用catch try catch?
【发布时间】:2015-03-06 01:43:49
【问题描述】:

我的教授给了我们一个 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;
}

【问题讨论】:

    标签: c++ try-catch


    【解决方案1】:

    听起来他希望您将代码放在 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 导致程序混乱结束。在我看来,这更好,因为它往往更容易调试。但短期内按老师说的做可能会更容易,以后改掉所有这些坏习惯。

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2019-12-04
      • 1970-01-01
      • 2012-11-25
      • 2021-11-25
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      相关资源
      最近更新 更多