標準例外クラス (std::exception) を使用する
このステップでは、C++ における標準例外クラスについて学び、std::exception 階層を使用してさまざまな種類のランタイムエラーを処理する方法を学びます。C++ 標準ライブラリは、さまざまなエラーシナリオをカバーする事前定義済みの例外クラスのセットを提供しています。
WebIDE を開き、~/project ディレクトリに新しいファイル standard_exceptions.cpp を作成します。
touch ~/project/standard_exceptions.cpp
standard_exceptions.cpp に次のコードを追加します。
#include <iostream>
#include <stdexcept>
#include <limits>
double divideNumbers(double numerator, double denominator) {
// std::runtime_error を使用してゼロでの割り算をチェックする
if (denominator == 0) {
throw std::runtime_error("Division by zero is not allowed!");
}
return numerator / denominator;
}
void checkArrayIndex(int* arr, int size, int index) {
// std::out_of_range を使用して範囲外アクセスをチェックする
if (index < 0 || index >= size) {
throw std::out_of_range("Array index is out of bounds!");
}
std::cout << "Value at index " << index << ": " << arr[index] << std::endl;
}
int main() {
try {
// ゼロでの割り算の例外を示す
std::cout << "Attempting division:" << std::endl;
double result = divideNumbers(10, 0);
}
catch (const std::runtime_error& e) {
std::cout << "Runtime Error: " << e.what() << std::endl;
}
try {
// 配列インデックスが範囲外の例外を示す
int numbers[] = {1, 2, 3, 4, 5};
int arraySize = 5;
std::cout << "\nAccessing array elements:" << std::endl;
checkArrayIndex(numbers, arraySize, 2); // 有効なインデックス
checkArrayIndex(numbers, arraySize, 10); // 無効なインデックス
}
catch (const std::out_of_range& e) {
std::cout << "Out of Range Error: " << e.what() << std::endl;
}
return 0;
}
標準例外クラスを調べてみましょう。
-
std::exception:
- すべての標準例外の基底クラス
- エラーの説明を取得するための仮想
what() メソッドを提供する
-
一般的な派生例外クラス:
std::runtime_error:プログラム実行中にのみ検出できるランタイムエラー用
std::out_of_range:インデックスまたは反復子が有効範囲外の場合
- その他の一般的なクラスには、
std::logic_error、std::invalid_argument などがあります。
プログラムをコンパイルして実行します。
g++ standard_exceptions.cpp -o standard_exceptions
./standard_exceptions
実行結果の例:
Attempting division:
Runtime Error: Division by zero is not allowed!
Accessing array elements:
Value at index 2: 3
Out of Range Error: Array index is out of bounds!
標準例外クラスに関する要点:
- さまざまな種類のエラーを処理するための構造化された方法を提供する
- 各例外クラスは特定の目的を果たす
what() メソッドは説明的なエラーメッセージを返す
- より堅牢で情報の豊富なエラーハンドリングの作成に役立つ