C++ 异常处理

最经典的例子是除0异常

#include <iostream>
using namespace std;
int divide(int x, int y)
{
  if (y == 0) throw x;
  return x / y;
}
int main()
{
  try
  {
    cout << "4 / 2 = " << divide(4, 2) << endl;
    cout << "4 / 0 = " << divide(4, 0) << endl;
  }catch (int e)
  {
    cout << e << " is divided by 0" << endl;
  }
}

用法是在函数里throw
然后用catch捕获throw
前面加try

你可能感兴趣的:(C++ 异常处理)