C++での例外処理とオブジェクト破棄
C ++のデストラクタは、基本的に、オブジェクトが破棄されてシステムからメモリを解放するときに呼び出されます。クラスで例外がスローされると、catchブロックが実行される前にデストラクタが自動的に呼び出されます。
アルゴリズム
Begin Declare a class sample1. Declare a constructor of sample1. Print “Construct an Object of sample1” Declare a destructor of sample1. Print “Destruct an Object of sample1” Declare a class sample. Declare a constructor of sample2. Declare variable i of the integer datatype. Initialize i = 7. Print “Construct an Object of sample1”. Throw i. Declare a destructor of sample2. Print “Destruct an Object of sample2” Try: Declare an object s1 of class sample1. Declare an object s2 of class sample2. Ctach(int i) Print “Caught”. Print the value of variable i. End.
サンプルコード
#include <iostream>
using namespace std;
class Sample1 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
Sample2() {
int i =7;
cout << "Construct an Object of sample2" << endl;
throw i;
}
~Sample2() {
cout << "Destruct an Object of sample2" << endl;
}
};
int main() {
try {
Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}
} 出力
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
-
C++での例外処理の基本
C ++では、例外処理はランタイムエラーを処理するプロセスです。例外は、C++で実行時にスローされるイベントです。すべての例外は、std::exceptionクラスから派生します。処理可能なランタイムエラーです。例外を処理しない場合は、例外メッセージを出力してプログラムを終了します。 例外は、C ++標準では、プログラム内で使用できるクラスとして定義されています。親子クラス階層の配置を以下に示します。 C++の一般的な例外クラスは次のとおりです。 例外 説明 std ::exception これは、すべての標準C++例外の例外および親クラスです。 std ::
-
C#での例外処理とは何ですか?
例外は、プログラムの実行時に発生する問題です。次のキーワードは、C#の例外を処理します。 試してください tryブロックは、特定の例外がアクティブ化されているコードのブロックを識別します。 キャッチ catchキーワードは、例外のキャッチを示します。 最後に 例外がスローされるかどうかに関係なく、指定された一連のステートメントを実行します。 投げる プログラムに問題が発生すると、例外がスローされます。 C#プログラムでエラーを処理する例を見てみましょう- using System; namespace MyErrorHandlingApplication { &nb