设计一个堆栈类(例如8 9 w) 当推入堆栈的元素超过堆栈的容量时,它将抛出一个堆栈完整的异常; 当堆栈已满时将一个元素弹出堆栈时,它将抛出一个堆栈空异常。使用try和catch并给我一段主函数来测试它
时间: 2023-12-08 12:16:16 浏览: 12
好的,以下是使用 Python 实现的堆栈类和一个主函数来测试它:
```
class Stack:
def __init__(self, capacity):
self.capacity = capacity
self.stack = []
def push(self, element):
try:
if len(self.stack) == self.capacity:
raise Exception("Stack is full")
else:
self.stack.append(element)
except Exception as e:
print(e)
def pop(self):
try:
if len(self.stack) == 0:
raise Exception("Stack is empty")
else:
return self.stack.pop()
except Exception as e:
print(e)
def is_empty(self):
return len(self.stack) == 0
def is_full(self):
return len(self.stack) == self.capacity
def main():
s = Stack(5)
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
s.push(6) # Raises "Stack is full" exception
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop()) # Raises "Stack is empty" exception
if __name__ == '__main__':
main()
```
在主函数中,我们首先创建一个容量为 5 的堆栈实例。然后我们分别将数字 1 到 5 推入堆栈中,最后尝试将数字 6 推入堆栈中,这会引发 "Stack is full" 异常。接下来,我们从堆栈中弹出元素并将它们打印到控制台上,最后尝试从空堆栈中弹出元素,这会引发 "Stack is empty" 异常。在 `push` 和 `pop` 方法中,我们使用 try 和 except 来捕获异常并打印异常消息。