Bootstrap

C++ ——异常

异常是程序在运行期间产生的问题,是一种逻辑问题而非语法问题

1、抛出异常 

    //异常处理
    string st("admin");
    cout<<st.at(22)<<endl;  //系统自动抛出的异常

C++异常机制不完善,有时需要程序员手动抛出异常,使用throw关键字 

#include <iostream>
using namespace std;
double divide(double a,double b){
    //手动抛出异常
    if(b==0){
        throw "除数为0";  //会显示数据类型
    }
    return a/b;
}
int main(){
    cout<<divide(4,2)<<endl;
    cout<<divide(4,0)<<endl;
    return 0;
}

2、捕获异常 

如果有异常对象的抛出,可以使用try-catch代码块捕获异常

#include <iostream>
using namespace std;
double divide(double a,double b){
    if(b==0){
        throw "除数为0";  //会显示数据类型
    }
    return a/b;
}
int main(){
    try{
        //要捕获的可能出现异常的代码
        cout<<divide(4,2)<<endl;
        cout<<divide(4,0)<<endl;
    }catch(char const* error){ //char const*为"除数为0"的数据类型
        cout<<error<<endl;
    }
    cout<<"*******"<<endl;
    return 0;
}

注意: 

(1)try代码块中无异常抛出

        此时try代码块内代码正常执行,catch代码块无效。因此一定不会抛出异常的代码不要放置到try代码块中。

(2)捕获类型与异常类型不同

        此时try-catch失效,程序会把异常转交给上级处理。

(3)try代码块的异常代码后仍然存在代码

        try代码块中一旦出现异常,会直接跳转到catch代码块进行类型匹配,匹配成功进入catch代码块,执行完成后,try-catch结束;匹配失败后直接把异常交给上级处理

3、自定义异常

实际开发中,需要开发团队把自定义异常加入其中,标准异常的头文件可以使用#include <stdexcept> 

#include <iostream>
#include <stdexcept>
using namespace std;
//自定义异常
class My_except:public exception{
public:
    //throw()是异常规格说明,表示此函数不会抛出异常
    const char *ppp() const throw(){
        return "自定义异常" ;
    }
};
double divide(double a,double b){
    //手动抛出异常
    if(b==0){
        throw My_except();
    }
    return a/b;
}
int main(){
    //捕获自定义异常
    try{
        //要捕获的可能出现异常的代码
        cout<<divide(4,2)<<endl;
        cout<<divide(4,0)<<endl;
    }catch(const My_except& error){
        cout<<error.ppp()<<endl;
    }
    cout<<"*******"<<endl;
    return 0;
}
;