qfedu-cpp-level/day8/d4.cpp

72 lines
1.2 KiB
C++
Raw Permalink Normal View History

2023-08-02 19:23:29 +08:00
// 限制函数抛出异常
// throw() 声明表示不抛出任何异常
#include <iostream>
using namespace std;
class A
{
public:
int n;
public:
A(int n = 0) : n(n) {}
};
// throw() 声明表示不抛出任何异常
void show(int x) throw()
{
switch (x)
{
case 1:
throw 0;
break;
case 2:
throw 'a';
break;
case 3:
throw "abc";
break;
case 4:
throw 1.25;
break;
case 5:
throw A(100); // 抛出自定义类的对象
break;
// default 可以不写,因为前面已经覆盖了所有情况
}
cout << "x = " << x << endl;
}
int main()
{
cout << "输入一个整数: ";
int x;
cin >> x;
try
{
show(x);
}
catch (const int &error)
{
cout << "捕获异常: " << error << endl;
}
catch (const char &error)
{
cout << "捕获异常: " << error << endl;
}
catch (const char *error)
{
cout << "捕获异常: " << error << endl;
}
catch (const double &error)
{
cout << "捕获异常: " << error << endl;
}
catch (const A &error)
{
cout << "捕获异常: " << error.n << endl;
}
return 0;
}