try...catch

概念介绍

try...catch 异常捕获,当程序出一个错误时,可以进入错误处理函数,而不同退出,其中

  1. try statement 中是正常的代码块
  2. catch 是当出现一个错误时,会进入该模块进行错误处理。如遇到除 0 错误,段溢出错误
  3. throw 是抛出异常,这个异常不一定错误,只要是认为是有误的,都可以抛出来,扔到 catch 中去做处理
#include<iostream>
using namespace std;

double func(double num1, double num2) {
    if(0 == num1) {
        throw num1;
    }
    return num2/num2;
}

int func(int num){
    throw num;
}

int main()
{
    int num = -1;
    string str = "12";
    while (num <= 5)
    {
        num++;
        try
        {
            if(num == 0) {
                func(num, 2);
            }
            else if (num == 1){
                func(num);
            }
            else if(num == 2) {
                char ch = str.at(100);
                cout << "ch : " << ch << endl;
            }
            else if(num == 3) {
                throw "num = 3";
            }
            else if(num == 4) {
                char ch = str[num];
                cout << "ch : " << ch << endl;
            }
        }
        catch(int e)
        {
            cout << "int e: " << e << endl;
            cout << "num: " << num << endl;
        }
        catch(double e) {
            cout << "double e: " << e << endl;
            cout << "num: " << num << endl;
        }
        catch(const char* e) {
            cout << "string e: " << e << endl;
            cout << "num: " << num << endl;
        }
        catch(exception &e) {
            cout << "out of range" << endl;
        }
        
    }

    cout << "over" << endl;
    return 0;
    
}

运行结果:

double e: 0
num: 0
int e: 1
num: 1
out of range
string e: num = 3
num: 3
ch : 
over

补充

  1. 如果 throw 应该在错误之前抛出,如果真到了除 0 这种错误了,程序的控制权就不在自己手里了;
  2. catch throw 的用法应该是程序中考虑有什么样的异常,然后给出一个类型的 throw,然后在这里做错误处理,打印,或者直接跳过等操作
  3. GDB 中的 catchpoint 捕获的是 throw 发出的信号
  4. 除了基础数据类型,还可以抛出类类型出来捕获
  5. catch 捕获,必须要有一个throw,要么是自己程序中自己 throw,要么是库函数,或者STL里支持抛出异常,如果没有则不会被捕获

try...catch详细参考

posted @   王清河  阅读(306)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2019-09-06 Python3数据结构
点击右上角即可分享
微信分享提示