异常处理

本文介绍了C++中的异常处理机制,通过示例展示了如何使用标准库异常`std::out_of_range`报告运行时错误,并创建自定义异常类`emptyList`。此外,还探讨了可以抛出任何可复制和移动的对象作为异常,以及禁止拷贝和移动的影响。最后,展示了异常层次结构的一般概念。
摘要由CSDN通过智能技术生成

《c++程序设计语言(第四版)》2.4.3章节

异常负责报告运行时的错误。

1、标准库异常

#include <stdio.h>

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    int x[2]{1,2};
    int i = 2;
    try
    {
        if(i >= 2)
        {
            throw std::out_of_range("数组越界了");
        }
        else
        {
            debug x[i];
        }
    }
    catch(const std::out_of_range & exc)
    {
        debug exc.what() << "行:" << __LINE__ << "文件:" << __FILE__ << endl;
    }
    debug "hello";
}

2、自定义异常类

#include <stdio.h>

class emptyList :public std::exception
{
public:
    emptyList(QString msg):std::exception(),exceptionMsg(msg)
    {
    }
    QString getExceptionMsg() const
    {
        return this->exceptionMsg;
    }
private:
    QString exceptionMsg;
};

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    QList<int> list;
    try
    {
        if(list.isEmpty())
        {
            throw emptyList("容器为空");
        }
        else
        {
            debug list.size();
        }
    }
    catch(const emptyList & exc)
    {
        debug exc.getExceptionMsg() << "行:" << __LINE__ << "文件:" << __FILE__ << endl;
    }
    debug "hello";
}

3、抛出任何符合要求的对象作为异常,实际上只要一个类可以复制和移动,那么就可以抛出。

struct myError
{
    QString msg;
};

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    try
    {
        myError e{};
        e.msg = "测试";
        throw e;
    }
    catch(const myError & e)
    {
        debug e.msg;
    }
}

如果禁止拷贝和移动就不能抛出:

4、标准库异常层次一图流:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值