Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
936 views
in Technique[技术] by (71.8m points)

query about how to use the "raise" keyword in python

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The book defines the Empty class in "Fragment 6.1" in chapter 6 of the book. The description of this fragment is:

Code Fragment 6.1: Definition for an Empty exception class.

and the fragment itself is:

class Empty(Exception):
    """Error attempting to access an element from an empty container."""
    pass

Later sections of the book that make use of this class reference this code fragment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...