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

จับข้อยกเว้นคลาสฐานและคลาสที่ได้รับใน C ++


ในการดักจับข้อยกเว้นสำหรับทั้งคลาสฐานและคลาสที่ได้รับมา เราต้องวางบล็อก catch ของคลาสที่ได้รับก่อนคลาสฐาน มิฉะนั้น จะไม่ถึงบล็อก catch ของคลาสที่ได้รับ

อัลกอริทึม

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.

นี่คือตัวอย่างง่ายๆ ที่ catch ของคลาสที่ได้รับถูกวางไว้ก่อน catch ของคลาสฐาน ตอนนี้ให้ตรวจสอบเอาต์พุต

#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

นี่คือตัวอย่างง่ายๆ ที่ catch ของคลาสฐานถูกวางไว้ก่อน catch ของคลาสที่ได้รับ ตอนนี้ให้ตรวจสอบเอาต์พุต

#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.