c++异常处理
C++异常当然可以通过try...catch处理,不过没有finally关键词。C++资源的释放可以通过RAII实现。
RAII,也称为“资源获取就是初始化”,是c++等编程语言常用的管理资源、避免内存泄露的方法。它保证在任何情况下,使用对象时先构造对象,最后析构对象。
Destructors should never emit exceptions. If functions called in a destructor may throw, the destructor should catch any exceptions, then swallow them or terminate the program.
而且,也必须提供一个接口,让用户可以手动地释放资源。有机会自己处理这个可能的异常。
c++可以抛出一些标准的异常,比如:
- exception 最常见的问题
- runtime_error 运行时错误:仅在运行时才能检测到的问题
- range_error 运行时错误:生成的结果超出了有意义的值域范围
- overflow_error 运行时错误:计算上溢
- underflow_error 运行时错误:计算下溢
或者抛出任意一个自定义类。