在C++中處理point類的異常情況,通常需要考慮以下幾個方面:
point類成員函數時,使用try-catch塊來捕獲并處理異常。下面是一個簡單的point類示例,展示了如何處理異常情況:
#include <iostream>
#include <stdexcept>
class point {
private:
int x, y;
public:
point(int x = 0, int y = 0) : x(x), y(y) {
if (x < 0 || y < 0) {
throw std::invalid_argument("Coordinates must be non-negative.");
}
}
// 其他成員函數...
};
int main() {
try {
point p(-1, 2); // 這將拋出一個異常
// ... 其他代碼
} catch (const std::invalid_argument& e) {
std::cerr << "Caught an exception: " << e.what() << std::endl;
// ... 處理異常
}
return 0;
}
在這個示例中,point類的構造函數檢查輸入坐標是否為非負數。如果坐標無效,它將拋出一個std::invalid_argument異常。在main函數中,我們使用try-catch塊來捕獲并處理這個異常。