1、运行时错误与异常
#include<iostream>#include<string>using namespace std;int main() {string str = "hello world!";cout << str[100] << endl;return 0;}
不会检查下标越界,虽有逻辑错误但是程序正常运行,输出垃圾值。
#include<iostream>#include<string>using namespace std;int main() {string str = "hello world!";cout << str.at(100) << endl;return 0;}
2、捕获异常
1)
#include<iostream>#include<string>#include<exception>using namespace std;int main() {string str = "hello world!";try {cout << str[100] << endl;}catch(exception e) {cout << "1 - out of bound" << endl;}try {cout << str.at(100) << endl;}catch(exception &e) {cout << "2 - out of bound" << endl;}try {cout << str[10000000] << endl;}//发生了内存访问异常,但是没有捕获到异常catch(exception e) {cout << "3 - out of bound" << endl;}return 0;}

2)抛出异常的位置:只要抛出异常,就会被try检测到,然后就会跳转到catch语句
#include<iostream>using namespace std;int main() {try {throw "异常";cout << "12234567" << endl;}catch(const char* &e) {cout << e << endl;}return 0;}

3)但是 catch 和真正的函数调用又有区别:
- 真正的函数调用,形参和实参的类型必须要匹配,或者可以自动转换,否则在编译阶段就报错了。
- 而对于 catch,异常是在运行阶段产生的,它可以是任何类型,没法提前预测,所以不能在编译阶段判断类型是否正确,只能等到程序运行后,真的抛出异常了,再将异常类型和 catch 能处理的类型进行匹配,匹配成功的话就“调用”当前的 catch,否则就忽略当前的 catch。
3、多级catch
#include<iostream>#include<string>using namespace std;class Base {};class Derived : public Base {};int main() {try {throw Derived();cout << "1" << endl;}catch(int) {cout << "int" << endl;}catch(float) {cout << "float" << endl;}//发生了向上转型catch(Base) {cout << "Base" << endl;}catch(Derived) {cout << "Derived" << endl;}return 0;}
4、catch的类型转换
向上转型:派生类到基类的转换
非const到const转换
数组或函数指针的转换:catch形参,如果不是引用类型,数组名会转为数组指针,函数名会转为函数指针#include<iostream>#include<string>using namespace std;int main() {int nums[] = {1,2,3,4};try {throw nums;}catch(const int *) {cout << "类型转换" << endl;}return 0;}
4、exception
C++语言本身或者标准库抛出的异常都是 exception 的子类,称为标准异常(Standard Exception)。你可以通过下面的语句来捕获所有的标准异常
catch(exception &e)异常类型为引用类型,提高效率try{//可能抛出异常的语句}catch(exception &e){//处理异常的语句}
at函数检测下表是否越界,抛出异常,终止程序执行。
