C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ try/catch

在C++编程中,使用try/catch语句执行异常处理。 C++ try块用于放置可能发生异常的代码。 catch块用于处理异常。

没有try/catch的C++示例

#include <iostream>
using namespace std;
float division(int x, int y) {
   return (x/y);
}
int main () {
   int i = 50;
   int j = 0;
   float k = 0;
      k = division(i, j);
      cout << k << endl;
   return 0;
}
输出:
floating point exception (core dumped)  

C++尝试/捕获示例

#include <iostream>
using namespace std;
float division(int x, int y) {
   if( y == 0 ) {
      throw "Attempted to divide by zero!";
   }
   return (x/y);
}
int main () {
   int i = 25;
   int j = 0;
   float k = 0;
   try {
      k = division(i, j);
      cout << k << endl;
   }catch (const char* e) {
      cerr << e << endl;
   }
   return 0;
}
输出:
Attempted to divide by zero!
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4