我是編程新手,我開始使用C++編程:原理和實踐。在其中的一章中,它討論了錯誤以及如何處理錯誤。拋出一個運行時錯誤
這裏的代碼片段是我試圖實現的。在本書中,它聲明瞭error()將以系統錯誤消息加上我們作爲參數傳遞的字符串來終止程序。
#include <iostream>
#include <string>
using namespace std;
int area (int length, int width)
{
return length * width;
}
int framed_area (int x, int y)
{
return area(x-2, y-2);
}
inline void error(const string& s)
{
throw runtime_error(s);
}
int main()
{
int x = -1;
int y = 2;
int z = 4;
if(x<=0) error("non-positive x");
if(y<=0) error("non-positive y");
int area1 = area(x,y);
int area2 = framed_area(1,z);
int area3 = framed_area(y,z);
double ratio = double(area1)/area3;
system("PAUSE");
return EXIT_SUCCESS;
}
我得到的消息是「測試project.exe在0x7699c41f未處理的異常:微軟C++異常:性病:: runtime_error內存位置0x0038fc18。」
所以我的問題是,我是什麼做錯了我傳遞給error()的消息沒有通過?
「的章節之一是談論錯誤以及如何處理它們。「你讀過那章了嗎?因爲你沒有處理錯誤。 – 2014-10-03 00:29:59
看看C++關鍵字'try'和'catch'。如果您不使用這些關鍵字,則您的程序將在第一個例外時終止。 – RPGillespie 2014-10-03 00:41:24