抛出运行时错误

sta*_*a23 8 c++ error-handling

我是编程新手,我开始编程:使用 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;
}
Run Code Online (Sandbox Code Playgroud)

我收到的消息是“测试项目.exe 中 0x7699c41f 处未处理的异常:Microsoft C++ 异常:内存位置 0x0038fc18 处的 std::runtime_error ..”

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

Gil*_*pie 5

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