কম্পিউটার

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

  1. C++ এ গোলকধাঁধা II

  2. C++ এ গোলকধাঁধা

  3. C++ এ ব্যতিক্রম হ্যান্ডলিং বেসিক

  4. কিভাবে C# এ শূন্য ব্যতিক্রম দ্বারা ভাগ ক্যাপচার করবেন?