zoukankan      html  css  js  c++  java
  • C++异常处理(Exception Handling)

      在C++中引入了三种操作符来处理程序的出错情况,分别是:try  , throw  ,  catch

    1.基本的用法如下:

    try{
        //code to be tried
        throw exception;
    }
    catch(type exception)
    {
        //code to be executed in case of exception
    }

    操作过程为:

      (1)try语句块中的代码正常执行,当有异常发生时,代码使用关键字 throw 和一个参数来抛出一个异常,这个参数可以是任何有效的数据类型,它反映了异常的特征;

      (2)当异常发生时,即try语句块中有一条throw被执行时,catch语句块亦即被执行,接受来自throw抛出的参数

    Demo:

    #include<iostream>
    using namespace std;
    int main()
    {
        try
        {
            char * mystring;
            mystring = new char[20];
            if (mystring == NULL)
                throw "Allocate Failure";
            for (int i = 0;i <= 50;i++)
            {
                if (i > 19)    throw i;
                mystring[i] = 'a';
            }
        }
        catch (int i)        //当throw 抛出的参数为int类型时执行
        {
            cout << "Exception: Index " << i << " is out of range." << endl;
        }
        catch (char* str)    //当throw抛出的参数为char*(string)类型时执行
        {
            cout << "Exception: " << str << endl;
        }
        system("pause");
        return 0;
    }

    result:

  • 相关阅读:
    PythonStudy——格式化输入小练习
    PythonStudy——运算符优先级 Operator precedence
    PythonStudy——逻辑运算符 Logical Operators
    ExtJS动态创建组件
    常见报表的JS代码
    sqlserver学习
    读写分离与锁分离
    oracle链接原理
    读java并发编程笔记
    日志机制在编程中的作用
  • 原文地址:https://www.cnblogs.com/runningRain/p/5934019.html
Copyright © 2011-2022 走看看