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.