ในบทช่วยสอนนี้ เราจะพูดถึงวิธีจัดการกับการหารด้วยข้อยกเว้น Zero ใน 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