简体   繁体   中英

Exception Handling with Stack in C++

I have written a function for Stack where the function top() shows the top of the stack:

class RuntimeException{
    private:
    string errorMsg;
    public:
    RuntimeException(const string& err){errorMsg = err;}
    string getMessage() const {return errorMsg;}
    };

class StackEmpty : public RuntimeException{
public:
StackEmpty(const string& err) : RuntimeException(err){}
};

template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    try{
        if(empty()) throw StackEmpty("Top of Empty Stack");
        return S[t];
        }
    catch(StackEmpty& se){
        cout << se.getMessage()<<"\n";
        }
    }


int main()
{
    ArrayStack <int> A;

    cout << "######\n";
    cout << A.top() << "\n";
        cout << "######\n";

    }

It shows below compilation warning:

$ g++ -Wall Stack.cpp -o Stack
Stack.cpp: In member function `const E& ArrayStack<E>::top() const [with E = int]':
Stack.cpp:91:   instantiated from here
Stack.cpp:61: warning: control reaches end of non-void function

The Output is:

$ ./Stack
######
Top of Empty Stack
6649957
######

Can someone tell what the warning is about and how to resolve it ? Also what does the the number '6649957' in output signifies?

Thanks

In the case StackEmpty is thrown, function doesn't return anything, though it is supposed to return const E& .

template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    try{
        if(empty()) throw StackEmpty("Top of Empty Stack");
        return S[t];
        }
    catch(StackEmpty& se)
    {
        cout << se.getMessage()<<"\n";
        // Return operator is missing ! Possibly you want this:
        throw;
   }
}

Edit. This is the way to use exception thrown from the method. You need to catch an exception in the client code, and not in the method itself.

template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    if(empty()) throw StackEmpty("Top of Empty Stack");
    return S[t];
}

int main()
{
    ArrayStack <int> A;

    try
    {
        cout << "######\n";
        cout << A.top() << "\n";
        cout << "######\n";
    }
    catch(StackEmpty& se)
    {
        cout << se.getMessage()<<"\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM