• c++异常处理机制


      1.异常处理的实现

      

    #include<iostream>
    using namespace std;
    double divide(double,double);
    int main(){
        double f1=0.0,f2=0.0;
        try{
            cout<<"f1/f2="<<divide(f1,f2)<<endl;
        }
        catch(double){
            cout<<"被0除"<<endl;
        }
        return 0;
    }
    double divide(double x,double y){
        if(y==0)
            throw 0.0;
        return x/y;
    }

      运行结果:  被0整除

    #include<iostream>
    using namespace std;
    class OutOfBounds{
    public:
        OutOfBounds(int a){
            i=a;
        }
        int indexValue(){
            return i;
        }
    private:
        int i;
    };
    class Array{
    public:
        int &operator[](int i){
            if(i<0||i>=10){
                throw OutOfBounds(i);
                return a[i];
            }
        }
    private:
        int a[10];
    };
    int main(){
        Array a;
        try{
            a[3]=30;
            cout<<"a[3]  "<<a[3]<<endl;
            a[100]=100;
            cout<<"a[100]"<<a[100]<<endl;
        }
        catch(OutOfBounds error){
            cout<<"Subscript value "<<error.indexValue()<<" out of bounds.
    ";
        }
        return 0;
    }

    重载运算符号[],进行越界检查。如果下标为负或大于10,则出错。

    注意:重载运算符operator[]函数第一行的&符号是必需的。因为这个函数不仅返回数组元素的值,而且还返回这个元素本身(即左值),以便在一条赋值语句的左侧使用诸如a[3]的表达式,如表达式a[100]=1000;

      运行结果:

    2重新抛出异常和异常规范

    #include<iostream>
    using namespace std;
    void h(){
        throw 0;
    }
    void g(){
        try{
            h();
        }
        catch(int){
            cout<<"Catch in g
    ";
            throw;
        }
    }
    int main(){
        try{
            g();
        }
        catch(int){
            cout<<"Catch in main
    ";
        }
        
        return 0;
    }

    运行结果:

    3.标准库中的异常类

    #include<iostream>
    #include <exception>
    using namespace std;
    
    int main(){
        try{
            exception theError;//声明一个标准c++异常类exceptio的对象
            throw(theError);//抛出该异常类的对象
        }
        catch(const exception &theError){//捕捉标准c++异常类的对象
            cout<<theError.what()<<endl;//用waht成员函数显示出错原因
        }
        try{
            logic_error theLogicError("Logic Error!");//声明一个标准c++异常类logic_error的对象
            throw(theLogicError);//抛出该异常类的对象
        }
        catch(const exception &theLogicError){//捕捉标准c++异常类的对象
            cout<<theLogicError.what()<<endl;//用waht成员函数显示出错原因
        }
        return 0;
    }

    运行结果:

  • 相关阅读:
    IFNULL和isnull用法
    Python 进制转换 二进制 八进制 十进制 十六进制
    xhr是什么文件类型?
    from __future__ import unicode_literals
    sort is deprecated, use sort_values(inplace=True) for INPLACE sorting
    Autodesk View and Data API二次开发学习指南
    设置Mac 中保存对话框默认为扩展窗口
    [大数据学习研究] 错误排查,Hadoop集群部分DataNode不能启动
    IDEA 环境下更改Maven的仓库镜像提高下载速度
    [大数据学习研究] 4. Zookeeper-分布式服务的协同管理神器
  • 原文地址:https://www.cnblogs.com/liujunming/p/4578683.html
Copyright © 2020-2023  润新知