c++中栈异常处理
Exception Handling with Stack in C++
我为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";
}
}
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C :ScopeGuard vs返回支票和异常处理
- 异常处理期间的类型解析