如果我只是簡單地使用throw some_string;
,那麼我得到terminate called after throwing an instance of 'std::string'
。我怎樣才能得到一些打印輸出的字符串值實際顯示,例如,terminate called after throwing 'This is wrong'
,或類似的東西?如何用C++打印輸出
謝謝。
如果我只是簡單地使用throw some_string;
,那麼我得到terminate called after throwing an instance of 'std::string'
。我怎樣才能得到一些打印輸出的字符串值實際顯示,例如,terminate called after throwing 'This is wrong'
,或類似的東西?如何用C++打印輸出
謝謝。
通常,您應該拋出std::exception.
的子類如果未捕獲到異常,大多數C++實現自動打印出調用exception::what()
的結果。
#include <stdexcept>
int main()
{
throw std::runtime_error("This is wrong");
}
隨着GCC,此輸出:
terminate called after throwing an instance of 'std::runtime_error'
what(): This is wrong
Aborted
你必須從某個地方添加代碼來處理拋出的對象。如果你什麼都不做,那麼程序在調用中止時結束,結果是實現定義的。您的解決方案是在代碼中的某處添加一個catch塊,例如在主函數中。原因如下
你必須捕獲異常
#include <iostream>
#include <string>
int main(int argc, char *argv[]) try
{
throw std::string("This is a test");
return 0;
}
catch(const std::string &s)
{
std::cout << s << std::endl;
}
有趣的函數try-catch塊的使用,我忘記了這一點,注意這會導致main的隱式返回值,這意味着main將返回0,這可能不是你想要的,如果你報告錯誤條件當退出時 – karunski 2012-02-24 03:42:22
其實我試圖使用晦澀的形式 - 但我只是把它扔在我的主要func的標準模板 - 我沒有考慮返回值,我會假設值是未定義的,因爲'返回0 ;'不應該被執行 - 對吧? – 2012-02-24 04:00:16
@AdrianCornish:0的返回值不是來自'return 0;',這是由於在不返回'return'語句的情況下離開main相當於返回0。 – Mankarse 2012-02-24 04:48:55
但Windows。 :( – Arafangion 2012-02-24 02:41:37