ホームに戻る
 例外処理(try, throw, catch)

/*
*
*   例外処理(try, throw, catch)
*
*   例外を指定し、例外が起こったら
*   強制的に指定の場所に飛ばす処理を組むことができます。
*   try のブロック中で実行する関数では、
*   関数内で例外が起こった場合に値をつけて throw すると、
*   catch のブロックが値を受け取り処置をする。 
*
*/

#include <iostream>

using namespace std;

void f(int n) throw(int, char *){
  switch(n){
    case 0:
      throw -1;
    default:
      throw "error";
  }
}

int main(){
  try{
    f(0);
  }
  catch(int i){
    cout << i << endl;
  }
  catch(char *s){
    cout << s << endl;
  }

  try{
    f(1);
  }
  catch(int i){
    cout << i << endl;
  }
  catch(char *s){
    cout << s << endl;
  }

  int *p;

  try {
    p = new int[300000000000];
  }
  catch(bad_alloc x){
    cout << "p = new error." << endl;
    return 1;
  }

  delete [] p;

  return 0;
}

 結果

-1
error
p = new error.

inserted by FC2 system