2014-10-03 91 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

相关问题