异常处理机制
- C++异常处理机制是暂缓问题的处理,放到被调函数中去处理。
- 暂缓不是不处理只是延迟处理。如果不做处理会引发异常,系统会默认调用abort()函数终止程序
C++异常处理关键字
- try:捕获异常
- throw:抛出异常
- catch:捕获处理异常‘’
- try和catch的{}不能省略
- try和catch必须一起出现
无异常函数
//不存在异常
//老版本
int Max(int a,int b) throw()
{
//一旦声明为无异常函数,就不能抛出
return a > b ? a : b;
}
//新版本
int Max2(int a,int b) noexcept
{
//一旦声明为无异常函数,就不能抛出
return a > b ? a : b;
}
int Max3(int a,int b) noexcept(true)
{
//一旦声明为无异常函数,就不能抛出
return a > b ? a : b;
}
C++标准库中的异常类
- 标准库异常类体系
- 重写异常类
#include <iostream>
#include <exception>
class AllocError :public std::exception
{
public:
AllocError() :exception("内存申请错误")
{
}
//重写父类方法
char const* what() const
{
return exception::what();
}
};
void printData()
{
int* p = nullptr;
if (p == nullptr)
throw AllocError();
std::cout << "正常运行" << std::endl;
}
int main()
{
try
{
printData();
}
catch (AllocError& object)
{
std::cout << object.what() << std::endl;
}
}