学习网站:C语言网.
C语言基础:C语言基础.
笔记及源码gitee地址:C++基础笔记及源码.
编译器:Red Panda Dev-C++.
1.异常概念
// 1.程序的错误通常包括:语法错误、逻辑错误、运行异常; // 1.1 语法错误:程序代码不符合语法要求,在编译、链接时由编译器提示的错误; // 1.2 逻辑错误:编译没问题,可以运行;但程序的输出结果或执行过程不是预期的结果,逻辑错误需要不断调试、测试发现; // 1.3 运行异常:程序在运行过程中由于意外情况,造成的程序异常终止,如:内存不足、打开的文件不存在、除数为0等情况; // 2.对异常进行预料,进行预见性处理,避免程序崩溃,保障程序的健壮性,这种行为称为异常处理; #include2.异常处理机制try-catchusing namespace std; int main(){ int num1,num2; cout << "Please enter num1 and num2:" << endl; cin >> num1 >> num2; if(num2 == 0){ // 简单的异常捕捉; cout << "Exception.Divide 0!" << endl; } else{ cout << "num1 = " << num1 << endl; cout << "num2 = " << num2 << endl; cout << "num1 / num2 = " << num1 / num2 << endl; } return 0; }
#include3.标准异常exception处理类using namespace std; int main(){ int num1,num2; cin >> num1 >> num2; try{ if(num2 == 0){ throw "error!num2 == 0"; // 抛出一个字符串; } } catch(const char *str){ // 捕获到一个字符串; cout << str << endl; } catch(int){ cout << "Throw int" << endl; } return 0; }
// 1.所有异常类继承自exception基类; // 2.说明: // 2.1 使用new开辟内存时,如果空间不足,则抛出bad_alloc异常; // 2.2 使用dynamic_cast()进行动态类型转化失败,则抛出bad_typeid异常; // 2.3 在计算数值超过该类型表示的最大范围时,则抛出overflow_error异常,运算上溢;underflow_error异常,运算下溢; // 2.4 使用string类下标越界,则抛出out_of_range异常; // 3.标准异常类头文件 // 3.1 exception、bad_exception类在头文件exception中定义; // 3.2 bad_alloc类在头文件new中定义; // 3.3 bad_typeid类在头文件typeinfo中定义; // 3.4 ios_base::failure类在头文件ios中定义; // 3.5 其他异常类在stdexcept中定义;
#include#include #include using namespace std; int main(){ string *s; try{ s = new string("www.fuxi.com"); cout << s->substr(15,5); // substr:从指定位置开始,复制具有指定长度的子字符串; } catch(bad_alloc &t){ cout << "Exception occurred!" << t.what() << endl; } catch(out_of_range &t){ cout << "Exception occurred!" << t.what() << endl; } return 0; }



