I am learning about user-defined exceptions in python and I have tried to incorporate them in a basic python implementation of a stack. Objects of Stack class support push, pop and top operations. I have defined the following exceptions:
StackEmptyError: Raise an exception when pop/top operation is performed on an empty stack.InvalidStackOpError: Raise an exception when an invalid operation is attempted
Here is the code
class StackEmptyError(Exception):
"Raised when pop/top operation is performed on empty stack"
pass
class InvalidStackOpError(Exception):
"Raised when an invalid stack operation is attempted"
pass
class stack:
def __init__(self):
self.s = list()
def push(self, x):
self.s.append(x)
def pop(self):
if not len(self.s):
raise StackEmptyError
popped = self.s.pop()
return popped
def top(self):
if not len(self.s):
raise StackEmptyError
return self.s[-1]
def perform_stackops(operations, values):
st = stack()
val_idx = 0
for op in operations:
if op == "push":
st.push(values[val_idx])
val_idx += 1
elif op == "pop":
print(f"Popped Element - {st.pop()}")
elif op == "top":
print(f"Top Element - {st.top()}")
else:
raise InvalidStackOpError(f"Operation {op} is invalid")
operations = ["push", "push", "pop", "pop", "push", "top"]
values = [20, 10, 30]
perform_stackops(operations, values)
Is this the right way to define and raise user-defined exceptions in python? Can I improve this even further?