我是编程新手,我开始编程:使用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:Microsoft C++异常:在内存位置0x0038fc18的std::runtime_error。”

所以我的问题是,我传递给error()的消息没有传递,我在做什么错?

最佳答案

正如我在评论中提到的那样,您必须“捕获”“抛出”的错误,以便程序不会立即终止。您可以使用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;
}

07-28 01:33
查看更多