কম্পিউটার

C++ এ বেস এবং প্রাপ্ত ক্লাসের ব্যতিক্রম ধরা


বেস এবং ডিরাইভ ক্লাস উভয়ের জন্যই ব্যতিক্রম ধরতে হলে আমাদেরকে বেস ক্লাসের আগে ডিরাইভ ক্লাসের ক্যাচ ব্লক রাখতে হবে। অন্যথায়, প্রাপ্ত ক্লাসের ক্যাচ ব্লক কখনই পৌঁছানো যাবে না।

অ্যালগরিদম

Begin
   Declare a class B.
   Declare another class D which inherits class B.
   Declare an object of class D.
   Try: throw derived.
   Catch (D derived)
      Print “Caught Derived Exception”.
   Catch (B b)
      Print “Caught Base Exception”.
End.

এখানে একটি সাধারণ উদাহরণ যেখানে বেস ক্লাস ধরার আগে ডিরাইভড ক্লাসের ক্যাচ রাখা হয়েছে, এখন আউটপুট চেক করুন

#include<iostream>
using namespace std;
class B {};
class D: public B {}; //class D inherit the class B
int main() {
   D derived;
   try {
      throw derived;
   }
   catch(D derived){
      cout<<"Caught Derived Exception"; //catch block of derived class
   }
   catch(B b) {
      cout<<"Caught Base Exception"; //catch block of base class
   }
   return 0;
}

আউটপুট

Caught Derived Exception

এখানে একটি সাধারণ উদাহরণ যেখানে প্রাপ্ত ক্লাসের ক্যাচের আগে বেস ক্লাসের ক্যাচ রাখা হয়েছে, এখন আউটপুট পরীক্ষা করুন

#include<iostream>
using namespace std;

class B {};
class D: public B {}; //class D inherit the class B
int main() {
   D derived;
   try {
      throw derived;
   }
   catch(B b) {
      cout<<"Caught Base Exception"; //catch block of base class
   }
   catch(D derived){
      cout<<"Caught Derived Exception"; //catch block of derived class
   }
   return 0;
}

আউটপুট

Caught Base Exception
Thus it is proved that we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.

  1. C++ এ ফ্রেন্ড ক্লাস এবং ফাংশন

  2. C# এ বেস এবং ডিরাইভড ক্লাস কি?

  3. C# তে সহভক্তি এবং বৈপরীত্য

  4. পাইথন ব্যতিক্রম বেস ক্লাস