Oct 27, 2009

C++ Exception

Tutorial 1
2 

try {
  // code here
}
catch (int param) { cout << "int exception"; }
catch (char param) { cout << "char exception"; }
catch (...) { cout << "default exception"; }

Throw 什么都可以,不定义是 std::exception 及其派生类.

using namespace std;

void f(int i) throw(int)
{
 if(i==1)
  throw 3;
 if(i==2)
  throw runtime_error("hehe");

}

int main()
{
 for(int i=0;i<10;i++)
 {
  try
  {
   if(i==1)
    throw exception();

   if(i==3)
    throw runtime_error("RUN ERROR!");

   if(i==8)
    throw logic_error("LOGIC ERROR!");

  }
  catch(runtime_error err)
  {
   cout << err.what() << endl;

  }
  catch(logic_error err)
  {
   cout << err.what() << endl;
   break;

  }
  catch(exception err)
  {
   cout << err.what() << endl;
  }


  cout << i << endl;

 }

 try
 {
  f(1);
 }
 catch(int e)
 {
  cout << e << endl;
 }

 try
 {
  f(2);
 }
 catch(exception err)
 {
  cout << err.what() << endl;
 }

 return 0;
}
注意 f 抛出的 runtime_error 异常会被捕获

0 comments: