Trong hướng dẫn này, ta sẽ thảo luận cách xử lý ngoại lệ chia cho 0 (Divide by Zero) trong C++.
Chia cho 0 là hành vi không xác định trong toán học, cần xử lý đúng cách khi lập trình để tránh lỗi tại runtime.
Cách 1: Sử dụng lớp runtime_error
#include <iostream>
#include <stdexcept>
using namespace std;
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 = 12.5, denominator = 0, result;
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
} catch(runtime_error& e) {
cout << "Exception occurred" << endl << e.what();
}
return 0;
}
Kết quả
Exception occurred Math error: Attempted to divide by Zero
Cách 2: Tự định nghĩa lớp ngoại lệ
#include <iostream>
#include <stdexcept>
using namespace std;
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 = 12.5, denominator = 0, result;
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
} catch(Exception& e) {
cout << "Exception occurred" << endl << e.what();
}
return 0;
}
Kết quả
Exception occurred Math error: Attempted to divide by Zero
Cách 3: Sử dụng stack unwinding
#include <iostream>
#include <stdexcept>
using namespace std;
float CheckDenominator(float den) {
if(den == 0)
throw runtime_error("Math error: Attempted to divide by zero\n");
return den;
}
float Division(float num, float den) {
return num / CheckDenominator(den);
}
int main() {
float numerator = 12.5, denominator = 0, result;
try {
result = Division(numerator, denominator);
cout << "The quotient is " << result << endl;
} catch(runtime_error& e) {
cout << "Exception occurred" << endl << e.what();
}
return 0;
}
Kết quả
Exception occurred Math error: Attempted to divide by zero