mylogo

退役程序员的茶室 RetiredCoder.cn

← 返回上一页

C++编程基础: 16. 异常处理

2025-04-18 12:18:36

本系列文章是配合我发布的《C++编程基础》系列视频教程的知识点总结和补充。这一节我们来讲讲异常处理。

try…catch…捕获函数抛出的异常

类似于JAVA,C++也用try、catch这样的关键字来括起程序块对异常进行处理。try后面的大括号用来括起可能抛出异常的代码片段,抛出的异常,可能是在代码片段中直接由关键字throw抛出,也可能是来自于调用的某个函数,甚至可能来自函数中包含的另一个函数。

 例如,在视频中我举例的在try程序块中用throw抛出的异常,如果是来自于一个函数,在函数外也是可以被对应的catch捕获到的。

如果我把下面这段打印动态数组某个索引项具体值的代码段写成一个函数,可以这样改写:

原代码:

if(index>=myV.size()){    
    throw "The value is bigger than index.";
}else{    
    std::cout<<"The index is:"<<index<<std::endl;    
    std::cout<<"The item is:"<<myV[index]<<std::endl;
}

变为函数后的代码:

void printItem(const std::vector<int>& v, int index){    
    if(index>=v.size()){        
        throw "The value is bigger than index.";    
    }else{        
        std::cout<<"The index is:"<<index<<std::endl;        
        std::cout<<"The item is:"<<v[index]<<std::endl;    
    }
}

在主函数中调用这个printItem函数:

int main(int argc, const char * argv[]) {
    std::vector<int> myV={32,14,73,28,41,38,92};    
    int index = -1;    
    while(true){        
        std::cout<<"Please input an Integer:"<<std::endl;        
        try{            
            if(std::cin>>index&&std::cin.get()=='\n'){
                if(index<0){break;}else{                    
                    printItem(myV,index);                
                }            
            }else{                
                std::cin.clear();                
                std::cin.ignore(INT_MAX, '\n');                
                throw "The input is not an integer.";            
            }        
        }catch(const char* e){            
            std::cout<<e<<std::endl;        
        }    
    }    
    return 0;
}

std::exception异常基类

除了我们自主抛出的异常外,C++还有一些特定的异常类,它们都是继承了std::exception这个类,下图展示了这些异常的继承关系:

Image

例如下面这段代码,展示了当抛出一个运行时错误时的处理:

#include <iostream>
#include <exception>
int main(int argc, const char * argv[]){
    try {        
        bool is_error = true;        
        if (is_error) {            
            throw std::runtime_error("It's a runtime error!");        
        }else{            
            std::cout<<"It's OK!"<<std::endl;        
        }    
    }    
    catch (std::exception& e) {        
        std::cout << e.what() << std::endl;    
    }    
    return 0;
}

is_errortrue时运行结果:

It's a runtime error!

通过调用exception对象的函数what(),可以获得定义这个异常时给出的错误信息。