zoukankan      html  css  js  c++  java
  • c++异常处理函数

    注意: throw 抛出异常,catch 捕获异常,try 尝试捕获异常

    catch 中的参数类型要和throw 抛出的数据类型一致

    try
    {
        //可能抛出异常的语句
    }
    catch (异常类型1)
    {
        //异常类型1的处理程序
    }
    catch (异常类型2)
    {
        //异常类型2的处理程序
    }
    // ……
    catch (异常类型n)
    {
        //异常类型n的处理程序
    }

    例1:

     #include <iostream>

     #include <stdlib.h>

    using namespace std;
    
    enum index{underflow, overflow};
    
    int array_index(int *A, int n, int index);
    
    int main()
    {
        int *A = new int[10];
        for(int i=0; i<10; i++)
            A[i] = i;
        try
        {
            cout<<array_index(A,10,5)<<endl;
            cout<<array_index(A,10,-1)<<endl;
            cout<<array_index(A,10,15)<<endl;
        }
        catch(index e)
        {
            if(e == underflow)
            {
                cout<<"index underflow!"<<endl;
                exit(-1);
            }
            if(e == overflow)
            {
                cout<<"index overflow!"<<endl;
                exit(-1);
            }
        }
    
        return 0;
    }
    
    int array_index(int *A, int n, int index)
    {
        if(index < 0) throw underflow;
        if(index > n-1) throw overflow;
        return A[index];
    }
    这是用来处理数组越界的代码,throw 抛出的是枚举型的数据,因此catch 中的数据类型也是相应的枚举型
    C++语句中有默认的异常处理函数,会对异常做出处理。


  • 相关阅读:
    11月7日
    11月6日
    11月5日
    11月4日
    html5
    intern
    pjtool用到的数据库----oracle范畴
    运用的jdk版本如何查看
    JAVA 一句话技巧
    [ios 开发笔记]:一句话笔记
  • 原文地址:https://www.cnblogs.com/zxzmnh/p/10458170.html
Copyright © 2011-2022 走看看