Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การจัดการ Divide by Zero Exception ใน 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

ใช้ User Defined Exception Handling

ตัวอย่าง

#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

ใช้ Stack Unwinding

ตัวอย่าง

#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