C++异常

目录

知识点1【异常的概述】

常见的异常

知识点2【异常严格类型匹配】(了解)

 知识点3【栈解旋(unwinding)】(了解)

 知识点4【指定抛出异常的类型】(了解)

知识点5【异常的生命周期】(了解)

 知识点6【标准异常库】(了解)


知识点1【异常的概述】

常见的异常

异常处理就是处理程序中的错误。所谓错误是指在程序运行的过程中发生的一些异常事件 (如:除0溢出,数组下标越界,所要读取的文件不存在, 空指针,内存不足等等)

throw抛出异常 try....catch捕获异常

#include <iostream>

using namespace std;
int myDiv(int a, int b)
{
    if(b == 0)
        throw -1;
    return a/b;
}

void test01()
{
    try
    {
        //cout<<myDiv(-10, 10)<<endl;
        cout<<myDiv(-10, 0)<<endl;
    }
    catch(int e)
    {
        cout<<"捕获到异常:e ="<<e<<endl;
    }
    cout<<"后续代码"<<endl;
}

int main(int argc, char *argv[])
{
    test01();
    return 0;
}

知识点2【异常严格类型匹配】(了解)

#include <iostream>
#include <string>
using namespace std;
void fun01()
{
    //throw 10;
    //throw 'A';
    //throw 3.14f;
    throw string("hello");
}

void test01()
{
    try
    {
        fun01();
    }
    catch(int)
    {
        cout<<"捕获到int异常"<<endl;
    }
    catch(char)
    {
        cout<<"捕获到char异常"<<endl;
    }
    catch(float)
    {
        cout<<"捕获到float异常"<<endl;
    }
    catch(string)
    {
        cout<<"捕获到string异常"<<endl;
    }
    catch(...)
    {
        cout<<"捕获到异常"<<endl;
    }
}

int main(int argc, char *argv[])
{
    test01();
    return 0;
}

 知识点3【解旋(unwinding)】(了解)

异常被抛出后,从进入try,到异常被抛掷,这期间在栈上构造的所有对象,都会被自动析构.

class Data
{
public:
    Data()
    {
        cout<<"无参构造"<<this<<endl;
    }
    ~Data()
    {
        cout<<"析够函数"<<this<<endl;
    }
};

void test02()
{
    try
    {
        Data ob1;
        Data ob2;
        Data ob3;

        throw 10;

    }
    catch(int)
    {
        cout<<"捕获到int异常"<<endl;
    }
}

 

 知识点4【指定抛出异常的类型】(了解)

//可以抛出任何异常
void fun01()
{
    //throw 10;
    //throw 'A';
    //throw 3.14f;
    throw string("hello");
}
//该函数只能抛出int或char异常
void fun02() throw(int,char)
{

    //throw string("hello");//失败
    //throw 10;
//    throw 'A';
//    throw 3.14f;//失败
}
//不抛出任何类型的异常
void fun03() throw()
{
    throw 10;
}

知识点5【异常的生命周期】(了解)

如果抛出的异常由 MyException e 来接收,则进行一次拷贝构造

class MyException
{
public:
    MyException()
    {
        cout<<"MyException无参构造"<<this<<endl;
    }
    MyException(const MyException &ob)
    {
        cout<<"MyException拷贝构造"<<endl;
    }

    ~MyException()
    {
        cout<<"MyException析够函数"<<this<<endl;
    }
};

void doWork()
{
    throw MyException();
    //throw new MyException;
}
void test03()
{
    try
    {
        doWork();
    }
    catch (MyException e)//会发生拷贝构造
    {
        cout << "捕获 异常" << endl;
    }
}

如果抛出的异常,由 MyException &e 或 MyException *e(引用或指针)来接收,则不进行拷贝构造,只传递抛出变量的地址。但是对于指针需要我们手动回收

 知识点6【标准异常库】(了解)

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值