2014-10-03 87 views
0

我是編程新手,我開始使用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()的消息沒有通過?

+4

「的章節之一是談論錯誤以及如何處理它們。「你讀過那章了嗎?因爲你沒有處理錯誤。 – 2014-10-03 00:29:59

+1

看看C++關鍵字'try'和'catch'。如果您不使用這些關鍵字,則您的程序將在第一個例外時終止。 – RPGillespie 2014-10-03 00:41:24

回答

0

正如我在我的評論中提到的,你必須「捕捉」你「拋出」的錯誤,以防止程序立即終止。你可以「捕獲」拋出的異常與try-catch塊,像這樣:

#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; 

    try 
    { 
     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; 
    } 
    catch (runtime_error e) 
    { 
     cout << "Runtime error: " << e.what(); 
    } 

    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 
+0

謝謝。因爲這本書沒有正確解釋它,所以清除了它。 – stanna23 2014-10-03 09:06:30

0

首先,我不知道你的程序是如何編譯,則需要包括stdexcept

要回答,您程序的行爲完全如其。您可能錯過了閱讀中的某些內容,但不幸的是您從Microsoft獲得的錯誤消息。下面是輸出我得到的OSX:

terminate called after throwing an instance of 'std::runtime_error' 
    what(): non-positive x 
Abort trap: 6 

OSX給我的what()內容,所以至少我知道這是我的異常終止該程序。

我假設你正在使用Visual Studio,但我不知道如何使用它。也許,如果你在調試模式下編譯程序,它會給出更多的輸出來判斷拋出異常的實際情況。

無論如何,這可能不是你想要的程序結束,你應該把可能中try塊拋出異常的代碼的方式,然後catch它:

int main() 
{ 
    try 
    { 
     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; 
    } 
    catch(const std::runtime_error& error) 
    { 
     std::cout << error.what() << '\n'; 
    } 

    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 
+0

謝謝!我得到了我塞滿的地方! – stanna23 2014-10-03 09:07:00

相關問題