C++中异常处理
2015-12-30 10:51
465 查看
//异常处理 #include <iostream> using namespace std; int Test(int i) { if(i == 1) { throw 0; } else if(i == 2) { throw 'a'; } else if(i == 3) { throw "Hello"; } else if(i == 4) { throw 0.5; } return i; } int main() { for(int i=0;i<5;i++) { try { cout << Test(i) << endl;; } //根据返回值类型来判断选择哪个catch语句 catch(int e) { //同一数据类型可以使用if来判断 if(e == 0) { cout << "Exception : int " << e << endl; } else { cout << "Exception : int !0" << e << endl; } } catch(char e) { cout << "Exception : char " << e << endl; } catch(const char* e) { cout << "Exception : const char* " << e << endl; } catch(double e) { cout << "Exception : double " << e << endl; } } return 0; }
//异常处理 #include <iostream> using namespace std; int Test(int i) { if(i == 1) { throw 0; } else if(i == 2) { throw 'a'; } else if(i == 3) { throw "Hello"; } else if(i == 4) { throw 0.5; } return i; } int main() { for(int i=0;i<5;i++) { try { cout << Test(i) << endl;; } catch(...) //捕获任意类型的异常 { cout << "Exception!"<< endl; } } return 0; }
//异常处理 #include <iostream> using namespace std; int Test(int i) { if((6 <= i)&&(i <= 8)) { throw 0; } return i; } int main() { try { for(int i=0;i<10;i++) { try { cout << Test(i) << endl;; } catch(int e) { cout << "Exception!" << e << endl; throw e; //catch再次抛出异常 } } } catch(int e) { cout << "Catch : " << e << endl; } return 0; }
相关文章推荐
- C++多态之继承7-多重继承
- C语言宏定义使用技巧
- C语言宏定义和宏定义函数
- Flume thrift source C++ Demo
- Keil STM32 C++混合编程要点
- C++强制类型转换
- C++ namespace + std::bind std::function
- 5、vc++设置Excel颜色
- GDB 调试
- C语言:二叉树的中序遍历
- 神奇的多态
- 学习C和C++的9点经验总结
- qt实现公历转农历,C++亦可用
- C中多线程开发
- C++必学知识点
- C/C++多种方法获取文件大小
- 黑马程序员-C语言-管理系统细节实现
- 【C++ STL应用与实现】19: 迭代器特性-iterator traits
- C/C++中的内存管理
- c++ 使用管道获取CMD命令结果