C++でのゼロ除算例外の処理
このチュートリアルでは、C++でゼロ除算例外を処理する方法について説明します。
ゼロ除算は数学では未定義のエンティティであり、ユーザー側でエラーが返されないように、プログラミング中に適切に処理する必要があります。
runtime_errorクラスの使用
例
#include <iostream>
#include <stdexcept>
using namespace std;
//handling divide by zero
float Division(float num, float den){
if (den == 0) {
throw runtime_error("Math error: Attempted to divide by Zero\n");
}
return (num / den);
}
int main(){
float numerator, denominator, result;
numerator = 12.5;
denominator = 0;
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
}
catch (runtime_error& e) {
cout << "Exception occurred" << endl << e.what();
}
} 出力
Exception occurred Math error: Attempted to divide by Zero
ユーザー定義の例外処理の使用
例
#include <iostream>
#include <stdexcept>
using namespace std;
//user defined class for handling exception
class Exception : public runtime_error {
public:
Exception()
: runtime_error("Math error: Attempted to divide by Zero\n") {
}
};
float Division(float num, float den){
if (den == 0)
throw Exception();
return (num / den);
}
int main(){
float numerator, denominator, result;
numerator = 12.5;
denominator = 0;
//trying block calls the Division function
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
}
catch (Exception& e) {
cout << "Exception occurred" << endl << e.what();
}
} 出力
Exception occurred Math error: Attempted to divide by Zero
スタック巻き戻しの使用
例
#include <iostream>
#include <stdexcept>
using namespace std;
//defining function to handle exception
float CheckDenominator(float den){
if (den == 0) {
throw runtime_error("Math error: Attempted to divide by zero\n");
}
else
return den;
}
float Division(float num, float den){
return (num / CheckDenominator(den));
}
int main(){
float numerator, denominator, result;
numerator = 12.5;
denominator = 0;
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
}
catch (runtime_error& e) {
cout << "Exception occurred" << endl << e.what();
}
} 出力
Exception occurred Math error: Attempted to divide by Zero
-
C++の迷路
空のスペースと壁のある迷路の中にボールがあるとします。これで、ボールは上、下、左、右などの任意の方向に転がることで空のパスを通過できますが、壁にぶつかるまで転がりが止まりません。ボールが止まると、次の方向を選択できます。 ボールの位置、目的地、迷路を開始し、ボールが目的地に止まるかどうかを確認する必要があります。迷路は1つの2D配列で表されます。ここで、1は壁を示し、0は空きスペースを示します。迷路の境界はすべて壁です。開始座標と宛先座標は、行と列のインデックスで表されます。 したがって、入力が2D配列で表される迷路のようなものである場合 0 0 1 0 0
-
C++での例外処理の基本
C ++では、例外処理はランタイムエラーを処理するプロセスです。例外は、C++で実行時にスローされるイベントです。すべての例外は、std::exceptionクラスから派生します。処理可能なランタイムエラーです。例外を処理しない場合は、例外メッセージを出力してプログラムを終了します。 例外は、C ++標準では、プログラム内で使用できるクラスとして定義されています。親子クラス階層の配置を以下に示します。 C++の一般的な例外クラスは次のとおりです。 例外 説明 std ::exception これは、すべての標準C++例外の例外および親クラスです。 std ::