文章目录
C++ 异常处理
1. 异常
1.1 异常概述
1.2 异常案例
1.2.1 除以零的操作
#include <iostream>
using namespace std;
int my_div(int n1, int n2);
int main(int argc, char const *argv[])
{
/*
try 尝试
大括号中是有可能存在异常的代码
*/
try
{
int ret = my_div(10, 0);
}
catch(int e)
{
// catch 捕获异常,需要提供当前异常的类型
// 处理异常
cout << "int 类型异常 除数不得为 0" << endl;
}
catch (double e)
{
cout << "double 类型异常 除数不得为 0" << endl;
}
catch (char e)
{
cout << "char 类型异常 除数不得为 0" << endl;
}
catch (...)
{
// catch (...) 表示捕获任意类型异常,但是只能兜底
cout << "任意类型异常 除数不得为 0" << endl;
}
return 0;
}
int my_div(int n1, int n2)
{
/*
n1 / n2 就是一段有隐患的代码
如果 n2 的结果为 0,会导致代码运行时报错【浮点数例外(核心已转储)】
*/
if (0 == n2)
{
/*
throw 扔
throw 之后是一个整数 -1,计算机认为,
当前函数【抛出】了一个 int 类异常
*/
// throw -1;
// throw -0.1;
// throw '\0';
throw -0.5F;
}
return n1 / n2;
}
1.2.1 数组中处理异常情况
int remove(int arr[], int capacity, int index)
{
// 判断用户指定下标位置是否合法
if (inedx < 0 || index > capacity - 1)
{
cout << "指定删除数据下标位置不合法!" << endl;
/*
当前函数返回值数据类型为 int 类型,
函数运行失败返回任何一个整数数据都无法明确告知调用者,
函数运行失败,因为任何一个整数都有可能是数组中存储的数据内容。
需要使用【C++ 异常】来解决问题
目前使用 exit(int exit_status) 来终止函数操作
*/
exit(EXIT_FALURE);
}
}
#include <iostream>
#include <exception>
using namespace std;
// 找出指定下标对应的元素
int find(int arr[], int capacity, int index);
int main(int argc, char const *argv[])
{
int arr[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
try
{
/*
find 函数抛出了一个 out_of_range 异常
当前代码在异常条件判断触发了异常抛出
并且 out_of_range 异常中,带有对应的异常信息,
可以在代码中展示对应异常信息,告知用户代码情况
*/
int ret = find(arr, 10, 12);
// 一旦出现异常,代码直接终止!!
cout << "ret : " << ret << endl;
cout << "try 大括号中 代码运行中" << endl;
}
catch(out_of_range e)
{
// catch 捕获异常之后,代码可以正常运行, C++认为当前代码一切正常
std::cerr << e.what() << '\n';
}
cout << "代码运行中" << endl;
return 0;
}
int find(int arr[], int capacity, int index)
{
if (index < 0 || index > capacity -1)
{
// cout << "用户指定的下标不合法!" << endl;
throw out_of_range("用户提供的下标不合法!");
}
return arr[index];
}