1、运行时错误与异常

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. int main() {
  5. string str = "hello world!";
  6. cout << str[100] << endl;
  7. return 0;
  8. }

image.png 不会检查下标越界,虽有逻辑错误但是程序正常运行,输出垃圾值。

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. int main() {
  5. string str = "hello world!";
  6. cout << str.at(100) << endl;
  7. return 0;
  8. }

image.png at函数检测下表是否越界,抛出异常,终止程序执行。

2、捕获异常

1)

  1. #include<iostream>
  2. #include<string>
  3. #include<exception>
  4. using namespace std;
  5. int main() {
  6. string str = "hello world!";
  7. try {
  8. cout << str[100] << endl;
  9. }
  10. catch(exception e) {
  11. cout << "1 - out of bound" << endl;
  12. }
  13. try {
  14. cout << str.at(100) << endl;
  15. }
  16. catch(exception &e) {
  17. cout << "2 - out of bound" << endl;
  18. }
  19. try {
  20. cout << str[10000000] << endl;
  21. }
  22. //发生了内存访问异常,但是没有捕获到异常
  23. catch(exception e) {
  24. cout << "3 - out of bound" << endl;
  25. }
  26. return 0;
  27. }

image.png
2)抛出异常的位置:只要抛出异常,就会被try检测到,然后就会跳转到catch语句

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. try {
  5. throw "异常";
  6. cout << "12234567" << endl;
  7. }
  8. catch(const char* &e) {
  9. cout << e << endl;
  10. }
  11. return 0;
  12. }

image.png
3)但是 catch 和真正的函数调用又有区别:

  • 真正的函数调用,形参和实参的类型必须要匹配,或者可以自动转换,否则在编译阶段就报错了。
  • 而对于 catch,异常是在运行阶段产生的,它可以是任何类型,没法提前预测,所以不能在编译阶段判断类型是否正确,只能等到程序运行后,真的抛出异常了,再将异常类型和 catch 能处理的类型进行匹配,匹配成功的话就“调用”当前的 catch,否则就忽略当前的 catch。

    3、多级catch

    1. #include<iostream>
    2. #include<string>
    3. using namespace std;
    4. class Base {};
    5. class Derived : public Base {};
    6. int main() {
    7. try {
    8. throw Derived();
    9. cout << "1" << endl;
    10. }
    11. catch(int) {
    12. cout << "int" << endl;
    13. }
    14. catch(float) {
    15. cout << "float" << endl;
    16. }
    17. //发生了向上转型
    18. catch(Base) {
    19. cout << "Base" << endl;
    20. }
    21. catch(Derived) {
    22. cout << "Derived" << endl;
    23. }
    24. return 0;
    25. }
    image.png

    4、catch的类型转换

    向上转型:派生类到基类的转换
    非const到const转换
    数组或函数指针的转换:catch形参,如果不是引用类型,数组名会转为数组指针,函数名会转为函数指针
    1. #include<iostream>
    2. #include<string>
    3. using namespace std;
    4. int main() {
    5. int nums[] = {1,2,3,4};
    6. try {
    7. throw nums;
    8. }
    9. catch(const int *) {
    10. cout << "类型转换" << endl;
    11. }
    12. return 0;
    13. }
    image.png

    4、exception

    C++语言本身或者标准库抛出的异常都是 exception 的子类,称为标准异常(Standard Exception)。你可以通过下面的语句来捕获所有的标准异常
    1. try{
    2. //可能抛出异常的语句
    3. }catch(exception &e){
    4. //处理异常的语句
    5. }
    catch(exception &e)异常类型为引用类型,提高效率