很难理解c++的异常处理

Having a tough time understanding exception handling c++

本文关键字:异常处理 c++ 难理解      更新时间:2023-10-16

在观看了在线教程并阅读了相关内容后,我很难理解异常处理。我试图通过测试驱动开发,但我做不到。目前我得出的结论是这样的。我应该使用这个结构体

struct ArrayException
{
    ArrayException(string newMessage = "error") :message(newMessage)
    {
    }
    string message;
};

第一次尝试。

int sum(int* theArray, unsigned int arraySize)
{
    try
    {
        if (theArray = NULL)
        {
            throw ArrayException("NULL ARRAY REFERENCE");
        }
    }
    catch (int* param)
    {
        cout << "you can't have " << param << " as an array size";
    }
    int sum = 0;
    for (int i = 1; i < arraySize; i++)
    {
        sum += theArray[i];
    }
    return sum;
}

我也试过这样做。

int sum(int* theArray, unsigned int arraySize)
{
    if (theArray = NULL)
    {
        throw ArrayException("NULL ARRAY REFERENCE");
    }
    else
    {
        int sum = 0;
        for (int i = 1; i < arraySize; i++)
        {
            sum += theArray[i];
        }
        return sum;
    }
}

虽然帖子没有特别提到,但我认为问题是为什么没有捕获异常?答案很简单——因为抛出的异常是ArrayException类型的,而catch是用int*类型完成的。

了解这些东西的最好方法是π α ντα ρ ε ω推荐的:找一本好书。这里是一个开始选择书籍的好地方:权威c++图书指南和列表

剩下的是一个代码块,在我认为需要的地方加了注释。

#include <iostream>
// removed the using namespace std;
struct ArrayException
{
    ArrayException(std::string newMessage = "error") :
            message(newMessage)
    {
    }
    std::string message;
};
int sum(int* theArray, size_t arraySize) // change made here:
    // size_t better suited than unsigned int for indexes
{
    //throw std::out_of_range("BOOM!"); //uncomment to trigger a std::exception
    //throw 42; // uncomment to trigger the unknown exception
    if (theArray == NULL)
    {
        throw ArrayException("NULL ARRAY REFERENCE"); //perfect!
    }
    else
    {
        int sum = 0;
        for (size_t i = 0; i < arraySize; i++) // changes made here: 
            // size_t not int to get rid of signed/unsigned conflict
            // starting with array index 0, not 1
        {
            sum += theArray[i];
        }
        return sum;
    }
}
int main()
{
    try
    {
        sum (NULL, 10); // NULL address to force the exception
    }
    catch (ArrayException & param) // catch the custom exception
        // catch by reference where possible
    {
        std::cout << "This bad stuff happened: " << param.message << std::endl;
    }
    // extra stuff to show what can also be done
    catch (std::exception & stdexcpt) // catch any standard exceptions and 
                                  // print their message
    {
         std::cout << "Standard exception thrown: " << stdexcpt.what() << std::endl;
    }
    catch (...) // catch anything else that was thrown and doesn't 
                // correspond to any expectation 
    {
         std::cout << "No idea what happened." << std::endl;
    }
}