异常是一种在程序运行过程中可能会发生的错误。

异常没有被处理,会导致程序终止。

抛出异常

throw 异常信息

捕获异常

try
{
    // 可能会发送异常的代码
}
catch ( 异常类型 变量名 )
{
    // 处理代码
}
catch ( 异常类型 变量名 )
{
    // 处理代码
}

int func(int a, int b)
{
    if ( b == 0 ) throw "除数不能为0";
    return a / b;
}

int main()
{
    int a = 10, b = 0;
    int c;
    try
    {
        c = func(a, b);
    }
    catch ( const char *msg )
    {
        cout << "异常信息:" << msg << endl;
    }
    cout << c << endl;
    return 0;
}

捕获所有异常是catch (...)

异常的抛出声明

为了增强可读性和方便团队协作,如果函数内部可能会抛出异常,建议函数声明一下异常类型。

int func(int a, int b) throw(const char *) // 抛出声明
{
    if ( b == 0 ) throw "除数不能为0";
    return a / b;
}

int main()
{
    int a = 10, b = 0;
    int c;
    try
    {
        c = func(a, b);
    }
    catch ( const char *msg )
    {
        cout << "异常信息:" << msg << endl;
    }
    cout << c << endl;
    return 0;
}

自定义异常类型

class Exception
{
public:
    int code;
    string msg;
    Exception(int code, string msg) : code(code), msg(msg) {  }
};

int main()
{
    cout << 1 << endl;
    try
    {
        throw Exception(1, "异常信息");
    }
    catch(const Exception &e)
    {
        cout << "code:" << e.code << ", msg:" << e.msg << endl;
    }
    cout << 2 << endl;
    return 0;
}

标准异常(std)

image-20210731173400857

异常 描述
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 当发生数学下溢时,会抛出该异常。