C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C++での基本クラスと派生クラスの例外のキャッチ


基本クラスと派生クラスの両方の例外をキャッチするには、派生クラスの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.

これは、派生クラスのキャッチが基本クラスのキャッチの前に配置されている簡単な例です。ここで、出力を確認します

#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#での共変性と反変性

    クラスを効果的に処理するには、共分散と逆分散の概念を使用します。 次のことをクラスとして考えてみましょう。 1つはクラス2の基本クラスであり、2つは3つの基本クラスです。 class One { } class Two: One { } class Three : Two { } 基本クラスは派生クラスを保持できますが、その逆はできません。共分散を使用すると、基本型が期待される場所に派生型を渡すことができます。共分散は、C#の配列、インターフェイス、デリゲートなどで使用できます。 対比分散はパラメーター用です。基本クラスのパラメーターを持つメソッドは、共変性を持つ派生クラスのパラ

  2. Python例外基本クラス

    他の高級言語と同様に、Pythonにもいくつかの例外があります。問題が発生すると、例外が発生します。 ZeroDivisionError、AssertionErrorなどのさまざまな種類の例外があります など。すべての例外クラスはBaseExceptionクラスから派生しています。 コードは組み込みの例外を実行することも、コードでこれらの例外を発生させることもできます。ユーザーは、例外から独自の例外を派生させることができます クラス、または例外の他の子クラスから クラス。 BaseExceptionは、他のすべての例外の基本クラスです。ユーザー定義クラスをこのクラスから直接派生させること