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

C ++例外をスローする方法は?


例外処理は、例外を処理するために使用されます。 trycatchブロックを使用してコードを保護できます。例外は、コードブロック内のどこにでもスローできます。キーワード「throw」は、例外をスローするために使用されます。

これがC++言語でのスローの例です

#include <iostream>
using namespace std;

int display(int x, int y) {
   if( y == 0 ) {
      throw "Division by zero condition!";
   }
   return (x/y);
}

int main () {
   int a = 50;
   int b = 0;
   int c = 0;

   try {
      c = display(a, b);
      cout << c << endl;
   } catch (const char* msg) {
      cerr << msg << endl;
   }
   return 0;
}

出力

これが出力です

Division by zero condition!

  1. C++で例外はどのように機能しますか

    C ++では、例外処理はランタイムエラーを処理するプロセスです。例外は、C++で実行時にスローされるイベントです。すべての例外は、std::exceptionクラスから派生します。処理可能なランタイムエラーです。例外を処理しない場合は、例外メッセージを出力してプログラムを終了します。 例外は、C ++標準では、プログラム内で使用できるクラスとして定義されています。親子クラス階層の配置を以下に示します- C++の一般的な例外クラスは-です。 Sr.No。 例外と説明 1 std ::exception これは、すべての標準C++例外の例外および親クラスです。

  2. newを使用してC++で2D配列を宣言するにはどうすればよいですか

    動的2D配列は、基本的に配列へのポインターの配列です。これは、寸法が3x4の2D配列の図です。 アルゴリズム Begin    Declare dimension of the array.    Dynamic allocate 2D array a[][] using new.    Fill the array with the elements.    Print the array.    Clear the memory by deleting it. End サンプルコード