C++中網(wǎng)格的錯(cuò)誤處理和異常機(jī)制

c++
小樊
82
2024-09-14 11:36:55
欄目: 編程語言

在C++中,網(wǎng)格(Grid)通常是指一個(gè)二維數(shù)組,用于存儲(chǔ)和操作二維空間中的數(shù)據(jù)

  1. 越界檢查:在訪問網(wǎng)格元素時(shí),確保行和列索引在有效范圍內(nèi)。如果索引超出范圍,可以拋出一個(gè)異?;蚍祷匾粋€(gè)錯(cuò)誤碼。
class Grid {
public:
    // ...
    int& at(int row, int col) {
        if (row < 0 || row >= rows_ || col < 0 || col >= cols_) {
            throw std::out_of_range("Index out of bounds");
        }
        return data_[row][col];
    }

private:
    int rows_;
    int cols_;
    std::vector<std::vector<int>> data_;
};
  1. 初始化檢查:在創(chuàng)建網(wǎng)格時(shí),確保行數(shù)和列數(shù)大于0。如果不滿足條件,可以拋出一個(gè)異?;蚍祷匾粋€(gè)錯(cuò)誤碼。
class Grid {
public:
    Grid(int rows, int cols) {
        if (rows <= 0 || cols <= 0) {
            throw std::invalid_argument("Rows and columns must be greater than 0");
        }
        rows_ = rows;
        cols_ = cols;
        data_.resize(rows, std::vector<int>(cols));
    }

    // ...
};
  1. 內(nèi)存分配檢查:在分配內(nèi)存時(shí),確保分配成功。如果分配失敗,可以拋出一個(gè)異?;蚍祷匾粋€(gè)錯(cuò)誤碼。
class Grid {
public:
    // ...
    void resize(int newRows, int newCols) {
        if (newRows <= 0 || newCols <= 0) {
            throw std::invalid_argument("Rows and columns must be greater than 0");
        }

        try {
            data_.resize(newRows, std::vector<int>(newCols));
        } catch (const std::bad_alloc& e) {
            throw std::runtime_error("Memory allocation failed");
        }

        rows_ = newRows;
        cols_ = newCols;
    }

private:
    // ...
};
  1. 使用異常處理:在調(diào)用可能拋出異常的函數(shù)時(shí),使用try-catch語句來捕獲和處理異常。
int main() {
    try {
        Grid grid(3, 3);
        int value = grid.at(5, 5); // This will throw an exception
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what()<< std::endl;
        return 1;
    }

    return 0;
}

通過這些錯(cuò)誤處理和異常機(jī)制,你可以確保網(wǎng)格在使用過程中的健壯性和穩(wěn)定性。

0