c++中栈异常处理

Exception Handling with Stack in C++

本文关键字:异常处理 c++      更新时间:2023-10-16

我为Stack编写了一个函数,其中函数top()显示堆栈的顶部:

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";
    }

显示如下编译警告:

$ 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

输出是:

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

有人能告诉我这个警告是关于什么以及如何解决它吗?另外,输出中的数字"6649957"表示什么?

谢谢

在抛出StackEmpty的情况下,函数不返回任何东西,尽管它应该返回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;
   }
}

编辑。这是使用从方法抛出的异常的方法。您需要在客户端代码中捕获异常,而不是在方法本身中。

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";
    }
}