Skip to content
On this page

CPP_异常处理


标签:CPP/基础  
  • 在可能产生异常处用 throw 关键字抛出异常
  • try 的作用域中,遇到异常,将执行跳到 catch 部分执行
  • 抛出的异常没有类型限制,catch 需要对应类型
  • try 中可抛出多种类型异常,搭配多个 catch 语块
cpp
double my_div(int m, int n) {
  if (n == 0) {
    throw -1;
  } else {
    return (double)m / n;
  }
}

int main() {
  try {
    cout << my_div(520, 1314) << endl;
    cout << my_div(520, 0) << endl;
    cout << "不会执行" << endl;
  } catch (int e) {
    if (e == -1) {
      cout << "除数不能为0" << endl;
    }
  } catch (const char* e) {
    // ...
  }
  cout << "可正常执行" << endl;
}

Last updated: