标准异常都在头文件<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 | 当发生数学下溢时,会抛出该异常。 |
也可以自定义异常类型,如下代码:
-
#include <iostream>
-
#include <exception>
-
using
namespace
std;
-
-
struct MyException :
public exception
-
{
-
const char * what () const throw ()
-
{
-
return
"C++ Exception";
-
}
-
};
-
-
int main()
-
{
-
try
-
{
-
throw MyException();
-
}
-
catch(MyException& e)
-
{
-
std::
cout <<
"MyException caught" <<
std::
endl;
-
std::
cout << e.what() <<
std::
endl;
-
}
-
catch(
std::exception& e)
-
{
-
//其他的错误
-
}
-
}