C++ 抛异常处理
一、概念
C++ 标准的异常
C++ 提供了一系列标准的异常,定义在 <exception> 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:
下表是对上面层次结构中出现的每个异常的说明:
异常 | 描述 |
---|---|
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;
}