c++:使用 throw、try 和 catch
我只是想努力工作。 这是我的堆栈的头文件,我将我的 throw 放在“/* */”中以暂时忽略它。 http://codepad.org/0Pm2Hy6u
它适用于我弹出和推送时,所以如果已满则抛出错误或空,但有例外。我对这些都是新的。
在我的书中,它将 FullStack 和 EmptyStack 设置为... Class FullStack{}; (所以空类)与 EmptyStack 相同。
有人可以帮我解决这个问题吗?
这是一个简单的主要内容: http://codepad.org/dbk4Ke6C
我怎样才能让 try 和 catch 工作。 ex)当调用 stack.Push(item) 并且它已满时,我可以捕获错误并显示它
I am just trying to get throw, try and catch to work.
Here is my header file for my stack and I place my throw in "/* */" to ignore it for now.
http://codepad.org/0Pm2Hy6u
It is for when I pop and push so throw out error if it is full or empty with the exception. I am all new at these.
In my book it sets FullStack and EmptyStack as so... Class FullStack{}; (so empty class) and same for EmptyStack.
Could some one perhaps help me figure this out.
Here is a simple main: http://codepad.org/dbk4Ke6C
How can I get try and catch to work. ex) When calling stack.Push(item) and it is full I could catch the error and display it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里将版本修复为单个文件:
在此处查看实时版本:https://ideone.com/95gMc
简而言之:
using namespace
!你会让你的类的用户的生活变得痛苦,他们试图避免命名空间之间的冲突,我最小化了注释,因为内联引用有点长(注释应该发挥作用,IMO )
我可以建议:
从公共堆栈异常基类派生(还建议对异常类采用更一致的命名约定): 编辑对此进行了一定程度的修复。有关基本原理,请参阅这篇背景文章
这样,您始终可以捕获任何
StackException&
(通过引用)并一次性处理要处理异常,请使用如下内容:< /p>
编辑编辑示例以演示增强的异常类型和示例处理程序:
Here is fixed a version as a single file:
See it live here: https://ideone.com/95gMc
In short:
using namespace
in header files! You will make life miserable for users of your class that try to avoid clashes between namespacesI minimized the comments because it was a bit lengthy to quote inline (and comments should be pulling their weight, IMO)
May I suggest:
derive from a common stack exception base class (also suggests a more consistent naming convention for Exception classes): Edit fixed this up somewhat. For rationale, see this background article
that way you can always catch any
StackException&
(by reference) and handle either stack full/empty in one goto handle the exception, use something like this:
Edit example edited to demonstrate the enhanced exception types and a sample handler: