C++自定义异常实例

本文通过一个例子演示c++如何自定异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <exception>
using namespace std;

struct Div0Exception : public exception
{
const char* what() const throw()
{
return "divisor is 0";
}
};

int divide(int a, int b)
{
if (b == 0)
throw Div0Exception();
return a/b;
}

int main(void)
{
try {
divide(10, 0);
} catch (Div0Exception e) {
cout<<e.what()<<endl;
}
cout<<"测试自定义异常"<<endl;
return 0;
}