
学习视频链接
C++异常处理机制_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1jX4y1V7o4?spm_id_from=333.337.search-card.all.click
目录
一、第一个异常处理程序
二、获取返回值
三、处理不同的返回值类型
一、第一个异常处理程序
#include
#include
using namespace std;
float Div(int a, int b)
{
if (b == 0)
{
throw b;
}
return a / b;
}
int main(void)
{
int a = 10;
int b = 0;
float result = 0.0;
try
{
result = Div(a, b);
}
catch (int)
{
cout << "Div Error, b == 0" << endl;
}
cout << "result = " << result << endl;
return 0;
}
二、获取返回值
#include
#include
using namespace std;
float Div(int a, int b)
{
if (b == 0)
{
int x = 2;
throw x;
}
return a / b;
}
int main(void)
{
int a = 10;
int b = 0;
float result = 0.0;
try
{
result = Div(a, b);
}
catch (int x)
{
cout << "返回值:" << x << endl;
}
cout << "result = " << result << endl;
return 0;
}
三、处理不同的返回值类型
#include
#include
using namespace std;
float Div(int a, int b)
{
if (b == 0)
{
short x = 2;
throw x;
}
return a / b;
}
int main(void)
{
int a = 10;
int b = 0;
float result = 0.0;
try
{
result = Div(a, b);
}
catch (int x)
{
cout << "返回值:" << x << endl;
}
catch (short)
{
cout << "处理返回值为short类型的异常" << endl;
}
cout << "result = " << result << endl;
return 0;
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)