This code is borrowed from the book DATA STRUCTURE AND ALGORITHMS IN PYTHON by Michael t. Goodrich.
class ArrayStack:
def __init__(self):
self.data=[]
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self.data)==0
def push(self,e):
self.data.append(e)
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
else:
return self.data[-1]
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
else:
return self.data.pop()
Here, the author uses raise Empty("stack is empty')
to raise an error message, but the "Empty" keyword isn't proper to be used with raise, and it instead throws NameError
when i run the program. I don't get why the author used it here instead of using the Exception
keyword with raise.
It has been used in every data structure in this book , so i don't think it's a typing error.(I apologize if i am missing something basic)
question from:
https://stackoverflow.com/questions/65640786/query-about-how-to-use-the-raise-keyword-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…