C++基础知识(8)异常处理

1. 异常处理基础

异常:程序在执行期间产生的问题。
C++异常处理提供的三个关键字:
(1)throw:当问题出现时,程序会通过throw来抛出一个异常。
(2)catch:在你想处理问题的地方,通过catch来捕获异常。
(3)try:try通常后面跟着一个catch或多个catch块。

2. 异常处理常见问题

2.1 接收被除数

接收传递过来的被除数,我们难以判断被除数是否为0。

#include <iostream>
/*
* divide()函数
* 用于两int相除,且被除数为0抛出异常
**/
int divide(int divisior, int dividend)
{
    if (!dividend)
    {
        throw "dividend is zero"; // 抛出异常,用于throw接收
    }
    return divisior / dividend;
}
/*
* clientInputNum()函数
* 用于接收int类型的输入
**/
void clientInputNum(const std::string& str, int& num)
{
    std::cout << str << std::endl;
    while (std::cin >> num, !std::cin.eof())
    {
        if (std::cin.bad())
        {
            throw std::runtime_error("cin is corrupted");
        }
        if (std::cin.fail())
        {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '/n');
            std::cout << "cin format is error" << std::endl;
            continue;
        }
        break;
    }
}
/*
* testThrowMain()函数
* 使用catch进行异常处理
**/
void testErrorMain()
{
    int divisior = 0;
    int dividend = 0;
    clientInputNum("please input divisior", divisior);
    clientInputNum("please input dividend", dividend);
    try
    {
        std::cout << divide(divisior, dividend);
    }
    catch(const char* except) // “XXX”用char*接收,如果用string封装,则用string接收
    {
        std::cout << "exception occers, exception is : " << except << std::endl;
    }
    catch (...) // 捕获任何异常
    {
        std::cout << "exception occers, exception is : unknown error" << std::endl;
    }
}

2.2 接收文件名

接收文件名,如果文件不存在,抛出异常。

#include <iostream>
#include <fstream>
/*
* clientInputString()函数
* 用于接收string类型的输入
**/
void clientInputString(const std::string& str, std::string& userStr)
{
    std::cout << str << std::endl;
    while (std::cin >> userStr, !std::cin.eof())
    {
        if (std::cin.bad())
        {
            throw std::runtime_error("cin is corrupted");
        }
        break;
    }
}
/*
* outPutFileContentByFilrName()函数
* 用于根据文件名打开对应文件内容,且文件名不存在抛出异常
**/
void outPutFileContentByFilrName(const std::string& fileName)
{
    std::ifstream ifs(fileName);
    std::string fileContent;
    if (ifs.is_open())
    {
        while (ifs >> fileContent)
        {
            std::cout << fileContent << std::endl;
        }
        if (ifs.bad())
        {
            throw std::runtime_error("ifs is corrupted");
        }
        ifs.close();
    }
    else
    {
        if (ifs.bad())
        {
            throw std::runtime_error("ifs is corrupted");
        }
        if (ifs.fail())
        {
            throw std::string("file not exist");
        }
    }
}
/*
* testThrowMain()函数
* 使用catch进行异常处理
**/
void testErrorMain()
{
    std::string fileName;
    try
    {
        clientInputString("please input flie name", fileName);
        outPutFileContentByFilrName(fileName);
    }
    catch (const std::string& str)
    {
        std::cout << "exception occers, exception is : " << str << std::endl;
    }
    catch (...)
    {
        std::cout << "exception occers, exception is : unknown error" << std::endl;
    }
}

2.3 内存不足

在动态分配内存时,使用new操作,会抛出bad_alloc的异常,这就是内存不足的情况。
注意:对new的重载很重要

#include <iostream>
#include <memory>
#include <vector>
void testErrorMain()
{
    std::vector<std::shared_ptr<int>> shared_pr_int_vec;
    try
    {
        while (1) // 一直动态分配内存
        {
            std::shared_ptr<int> shared_pr(new int[1000000]()); // 就算使用智能指针也会有内存分配不够的情况
            shared_pr_int_vec.push_back(shared_pr);
        }
    }
    catch (const std::bad_alloc& except) // std::bad_alloc:内存空间不足
    {
        std::cout << "exception occers, exception is : " << except.what() << std::endl;
    }
    catch (...)
    {
        std::cout << "exception occers, exception is : unknown error" << std::endl;
    }
}

2.4 越界问题

/*
* 越界访问的问题
**/
void testErrorMain()
{
    std::vector<int> ivec{ 1, 2, 3, 4, 5 };
    try
    {
        ivec.at(10); // 越界访问的情况
    }
    catch (const std::out_of_range& except)
    {
        std::cout << "exception occers, exception is : " << except.what() << std::endl;
    }
    catch (...)
    {
        std::cout << "exception occers, exception is : unknown error" << std::endl;
    }
}
/*
* 类中[]越界访问的异常抛出
**/
template<typename T>
class Test
{
public:
    T& operator[](unsigned count) const
    {
        if (count >= data.size())
        {
            throw std::out_of_range("Test data is out of range");
        }
    }
private:
    std::vector<T> data;
};

3. C++的标准异常

C++提供了一系列标准的异常,定义在头文件exception中。
在这里插入图片描述
经常使用的就那么几个:
(1)bad_alloc:使用new分配内存失败就会抛出bad_alloc错误。
(2)out_of_range:容器越界访问就会抛出out_of_range错误。
(3)runtime_error:运行时错误,只有程序运行时才能检测到的错误。
(4)…:接收任何错误。

try
{
    ....
}
catch (const std::bad_alloc& except)
{
    std::cout << "exception occers, exception is : " << except.what() << std::endl;
}
catch (const std::out_of_range& except)
{
    std::cout << "exception occers, exception is : " << except.what() << std::endl;
}
catch (const std::runtime_error& except)
{
    std::cout << "exception occers, exception is : " << except.what() << std::endl;
}
catch (const std::exception& except) // exception父类能接收所有子类的对象
{
    std::cout << "exception occers, exception is : " << except.what() << std::endl;
}
catch (...)
{
    std::cout << "exception occers, exception is : unknown error" << std::endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值