forked from MadhavBahl/OOPS
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtryCatch.cpp
91 lines (81 loc) · 2.11 KB
/
tryCatch.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* ============================================================ */
/* ===== Sammple program to illustrate exception handling ===== */
/* ============================================================ */
// Make a calculator that operates only on positive numbers
#include<iostream>
using namespace std;
int add (int x, int y) {
if (x<0 || y<0) {
throw 10;
}
return x+y;
}
int sub (int x, int y) {
if (x<0 || y<0) {
throw 10;
} else if (x<y) {
throw 10.01;
}
return x-y;
}
int mul (int x, int y) {
if (x<0 || y<0) {
throw 10;
}
return x*y;
}
double divide (int x, int y) {
if (x<0 || y<0) {
throw 10;
} else if (y == 0) {
throw true;
}
return (double)x/y;
}
int main () {
int a,b;
char ch;
cout<<"A simple calculator";
cout<<"\nEnter the value of a: "; cin>>a;
cout<< "Enter the value of b: "; cin>>b;
cout<<"\na. add\nb. subtract\nc. multiply \nd divide"<<endl;
cout<<"\nYour Choice: "; cin>>ch;
if (ch == 'a' || ch == 'A') {
try {
int res;
res = add (a,b);
cout<<a<<" + "<<b<<" = "<<res;
} catch (int n) {
cout<< "Negative numbers not allowed";
}
} else if (ch == 'b' || ch == 'B') {
try {
int res;
res = sub (a,b);
cout<<a<<" - "<<b<<" = "<<res;
} catch (int i) {
cout<<"Negative numbers not allowed";
} catch (float j) {
cout<<a<<" is less than "<<b;
}
} else if (ch == 'c' || ch == 'C') {
try {
int res;
res = mul (a,b);
cout<<a<<" * "<<b<<" = "<<res;
} catch (int n) {
cout<< "Negative numbers not allowed";
}
} else if (ch == 'd' || ch == 'D') {
try {
double res;
res = sub (a,b);
cout<<a<<" / "<<b<<" = "<<res;
} catch (int i) {
cout<<"Negative numbers not allowed";
} catch (bool j) {
cout<<"Division by zero is not defined";
}
}
return 0;
}