-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_004.cpp
More file actions
52 lines (45 loc) · 1.21 KB
/
problem_004.cpp
File metadata and controls
52 lines (45 loc) · 1.21 KB
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
//Write a C++ program to illustrate exception handling concept using stack operation
//as an example
#include <iostream>
#include <stdexcept>
using namespace std;
const int MAX_SIZE = 5; // Maximum size of the stack
class Stack{
private:
int items[MAX_SIZE];
int top;
public:
Stack() : top(-1) {}
void push(int value) {
if (top >= MAX_SIZE - 1) {
throw overflow_error("Stack overflow");
}
items[++top] = value;
}
int pop() {
if (top < 0) {
throw underflow_error("Stack Underflow");
}
return items[top--];
}
};
int main() {
Stack stack;
try {
for (int i = 1; i <= MAX_SIZE + 1; i++) {
stack.push(i); // Try to push more elements than the stack can hold
cout << "Pushed: "<<i<<endl;
}
} catch (const exception& e){
cerr << "Exception: " << e.what() << endl;
}
try {
for (int i = 1; i <= MAX_SIZE + 1; i++) {
int value = stack.pop(); // Try to pop more elements than available
cout << "Popped: " << value << endl;
}
} catch (const exception& e) {
cerr << "Exception: " << e.what() << endl;
}
return 0;
}