কম্পিউটার টিউটোরিয়াল

C++-এ ডিবাইড বাই জিরো এক্সেপশন হ্যান্ডলিং


এই টিউটোরিয়ালে আমরা C++-এ ডিবাইড বাই জিরো (Divide by Zero) এক্সেপশন কীভাবে হ্যান্ডেল করতে হয় সেটা নিয়ে আলোচনা করব।

গণিতের দৃষ্টিতে শূন্য দিয়ে ভাগ করা অনির্ধারিত (undefined), এবং প্রোগ্রামিং-এ এটি ঠিকমতো হ্যান্ডেল করা দরকার যাতে ইউজার এন্ডে এরর রিটার্ন না করে।

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

  1. C++-এ The Maze II সমস্যা: গোলাপταν গেঁদের ন্যূনতম দূরত্ব

  2. C++-এ মেজ সমস্যা: বল দিয়ে পথ খুঁজে বের করা

  3. সি++-এ এক্সেপশন হ্যান্ডেলিং (Exception Handling) বেসিক্স

  4. C#-এ DivideByZeroException ক্যাপচার করা