C++ 抛异常处理

一、概念

C++ 标准的异常

C++ 提供了一系列标准的异常,定义在 <exception> 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:

C++ 异常的层次结构

下表是对上面层次结构中出现的每个异常的说明:

异常描述
std::exception该异常是所有标准 C++ 异常的父类。
std::bad_alloc该异常可以通过 new 抛出。
std::bad_cast该异常可以通过 dynamic_cast 抛出。
std::bad_exception这在处理 C++ 程序中无法预期的异常时非常有用。
std::bad_typeid该异常可以通过 typeid 抛出。
std::logic_error理论上可以通过读取代码来检测到的异常。
std::domain_error当使用了一个无效的数学域时,会抛出该异常。
std::invalid_argument当使用了无效的参数时,会抛出该异常。
std::length_error当创建了太长的 std::string 时,会抛出该异常。
std::out_of_range该异常可以通过方法抛出,例如 std::vector 和 std::bitset<>::operator[]()。
std::runtime_error理论上不可以通过读取代码来检测到的异常。
std::overflow_error当发生数学上溢时,会抛出该异常。
std::range_error当尝试存储超出范围的值时,会抛出该异常。
std::underflow_error当发生数学下溢时,会抛出该异常。

定义新的异常

您可以通过继承和重载 exception 类来定义新的异常。下面的实例演示了如何使用 std::exception 类来实现自己的异常:

实例

#include "pch.h"
#include <iostream>
#include <stdexcept>
#include <exception>
#include <fstream>
#include <vector>

using namespace std;

struct MyException :public exception
{
    const char *what() const throw()
    {
        return "C++ Exception";
    }
};
int main()
{    
    try
    {
        throw MyException();
    }
    catch (MyException &e)
    {
        cout << "MyException caught" << endl;
        cout << e.what() << endl;
    }
    catch (exception &e)
    {
        //其他的错误
    }
    return 0;
}

这将产生以下结果:

MyException caught
C++ Exception

在这里,what() 是异常类提供的一个公共方法,它已被所有子异常类重载。这将返回异常产生的原因。

二、举例


#include "pch.h"
#include <iostream>
#include <stdexcept>
#include <exception>
#include <fstream>
#include <vector>

using namespace std;

void readIntegerFile(const string &fileName, vector<int> &dest)
{
    ifstream istr;
    int temp;
    istr.open(fileName);
    if (istr.fail())
    {
        throw invalid_argument("Unable to open the file");
    }
    while (istr >> temp)
    {
        dest.push_back(temp);
    }
    if (!istr.eof())
    {
        throw runtime_error("Error reading the file.");
    }
}


int main()
{
    vector <int> myInts;
    const string &fileName = "E:/test.txt";

    try
    {
        readIntegerFile(fileName, myInts);
    }
    catch (const runtime_error& e) {
        cerr << e.what() << endl;
        return 1;
    }
    catch (const invalid_argument& e) {
        cerr << e.what() << endl;
        return 1;
    }

    for (const auto&element : myInts)
    {
        cout << element << " ";
    }

    cout << endl;
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值