qfedu-cpp-level/day8/d2.cpp

30 lines
526 B
C++
Raw Normal View History

2023-08-02 19:23:29 +08:00
// 处理异常的语法
// 捕获基本数据类型的异常
#include <iostream>
using namespace std;
int div(int a, int b)
{
if (b == 0)
{
throw "除数不能为0"; // 抛出异常
}
return a / b;
}
int main()
{
cout << "-----aaaaa-----" << endl;
int ret = 0;
try // 捕获异常
{
ret = div(20, 0);
}
catch (const char *err) // 捕获异常
{
cout << "异常: " << err << endl; // 处理异常
}
cout << "ret = " << ret << endl;
return 0;
}