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++语句中有默认的异常处理函数,会对异常做出处理。


  • 相关阅读:
    python中几种数据类型常用的方法
    WSGI
    从开学到初赛的一些个人总结
    CSP-S2020 浙江 游记
    CF1416D Graph and Queries
    单次期望 O(1) 的RMQ
    P3177 [HAOI2015]树上染色
    CF835F Roads in the Kingdom/P1399 [NOI2013]快餐店
    P4381 [IOI2008]Island
    P5655 基础数论函数练习题
  • 原文地址:https://www.cnblogs.com/zxzmnh/p/10458170.html
Copyright © 2011-2022 走看看