julian8991
julian8991

Reputation: 1

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)

Upvotes: 0

Views: 134

Answers (1)

CryptoFool
CryptoFool

Reputation: 23089

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.

Upvotes: 4

Related Questions