C++学习笔记(二)

异常处理机制

案例一:被零整除异常
1.基本语法
2.异常是可以跨函数的
3.接收异常是可以不处理的 再抛
4.异常严格按照类型匹配

#include<iostream>
using namespace std;

void devide(int x, int y)
{
    if (y == 0)     throw x;//类似return,不执行后面的语句,throw 抛出
    cout << "result" << x / y << endl;
}

void main()
{
    try
    {
        devide(100, 10);
        devide(10, 0);
    }
    catch (int e)
    //catch(...) 相当于else。
    //catch 接异常,catch的类型要和throw的类型一致
    {
        cout << e << "被0整除3" << endl;
    }
    system("pause");
}

异常的设计目的:异常的引发和异常的处理不在同一个函数中。

栈解旋

throw时会把压栈在它上面的都析构

#include<iostream>
using namespace std;

class Test
{
public:
    int a;
    int b;
    Test(int a,int b)
    {
        this->a = a;
        this->b = b;
    }
    ~Test()
    {
        cout << "我被析构了" << endl;
    }
};
//void devide() throw(int,char)//代表限制throw能抛出异常的类型
void devide()//不写可以抛出任何类型
{

    Test t1(1,1), t2(2,2);
    cout << "i am going to throw" << endl;
    throw 1;
}

void main()
{
    try
    {
        devide();

    }
    catch (int e)//未使用e,则e可以不写
    {
        cout << "cath ur throw" << endl;
    }
    system("pause");
}
/*
screen printf:
/////////////////////
i am going to throw
我被析构了
我被析构了
cath ur throw
请按任意键继续. . .
/////////////////////
*/

异常类型异常变量的生命周期

1.接受异常时,使用一个异常变量,则拷贝构造异常变量
2.使用引用的时候,会使用throw时的对象

#include<iostream>
using namespace std;

void check(char *buf,char *buf2)//buf string copy to buf2
{
    if (buf == NULL)
        throw 1;
    if (buf2 == NULL)
        throw 2;
    if (*buf == 'a')//first charateristic=a
        throw 3;
    cout << "ok" << endl;//to be copied
}


void main()
{
    char buf[] = "abcde";
    char buf2[1024];
    try
    {
        check(buf, buf2);
    }
    catch (int e)
    {
    //switch-case!
        switch (e)
        {
        case 1:
            cout << "buf==NULL" << endl;
            break;
        case 2:
            cout << "buf2==NULL" << endl;
            break;
        case 3:
            cout << "process error" << endl;
            break;
        default:
            cout << "accident error" << endl;
            break;
        }
    }
    system("pause");
}
/*
我是构造函数
我是拷贝构造函数
未知类型
我是析构函数
我是析构函数
请按任意键继续. . .
*/

猜你喜欢

转载自blog.csdn.net/m0_37393277/article/details/62903703