c++:使用 throw、try 和 catch

发布于 2024-12-11 10:03:05 字数 482 浏览 0 评论 0原文

我只是想努力工作。 这是我的堆栈的头文件,我将我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生一梦 2024-12-18 10:03:05

这里将版本修复为单个文件:

在此处查看实时版本:https://ideone.com/95gMc

简而言之:

  • 您需要先定义异常类,然后才能抛出它们。将它们包含在 StackType 的头文件中,
  • 不要在头文件中使用(全局)using namespace!你会让你的类的用户的生活变得痛苦,他们试图避免命名空间之间的冲突,
  • 你需要将 1 个值推到堆栈上

我最小化了注释,因为内联引用有点长(注释应该发挥作用,IMO )

我可以建议:

  • 从公共堆栈异常基类派生(还建议对异常类采用更一致的命名约定): 编辑对此进行了一定程度的修复。有关基本原理,请参阅这篇背景文章

     #include ;
    
     struct StackException :虚拟 std::Exception 
     {  
         受保护:StackException() {}
     };
     结构 StackFullException : StackException 
     {
         char const* What() const throw() { return "StackFullException"; } }
     };
     结构 StackEmptyException : StackException
     {
         char const* What() const throw() { return "StackEmptyException"; } }
     };
    

    这样,您始终可以捕获任何 StackException&(通过引用)并一次性处理

  • 要处理异常,请使用如下内容:< /p>

    int main()
    {
         尝试 {
               // ....
         } catch (const StackException&e)
         {
             std::cerr << “哎呀,发生堆栈错误:” << e.what() << std::endl;
         }
    } 
    

编辑编辑示例以演示增强的异常类型和示例处理程序:

//Purpose: Header file for StackType. Containing all declerations and prototypes
#include <stdexcept>

struct StackException : virtual std::exception 
{  
    protected: StackException() {}
};
struct StackFullException : StackException 
{
    char const* what() const throw() { return "StackFullException"; }
};
struct StackEmptyException : StackException
{
    char const* what() const throw() { return "StackEmptyException"; }
};


template <class itemType>
class StackType
{
public:
    StackType   (int max);
    StackType   ();
    bool IsEmpty() const;
    bool IsFull () const;
    void Push   (itemType newItem);
    void Pop    ();
    itemType Top() const;
    ~StackType  (); // Destructor

private:
    int top;        // key:top of the stack
    int maxStack;   // max number of stack items
    itemType* list; // pointer to dynamically allocated memory
};

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*Implementation (StackStype.cpp)
StackType prototype functions*/

template <class itemType>
StackType<itemType>::StackType(int max)
{
    maxStack = max;
    top = -1;
    list = new itemType[maxStack];
}

template <class itemType>
StackType<itemType>::StackType()
{
    maxStack = 200;
    top = -1;
    list = new itemType[maxStack];
}

template <class itemType>
bool StackType<itemType>::IsEmpty() const
{
    return(top == -1);
}

template <class itemType>
bool StackType<itemType>::IsFull() const
{
    return(top == maxStack - 1);
}

template <class itemType>
void StackType<itemType>::Push(itemType newItem)
{
    if(IsFull())
    {
        throw StackFullException();
    }
    top++;
    list[top] = newItem;
}

template <class itemType>
void StackType<itemType>::Pop()
{
    if(IsEmpty())
    {
        throw StackEmptyException();
    }
    top--;
}

template <class itemType>
itemType StackType<itemType>::Top() const
{
    if(IsEmpty())
    {
        throw StackEmptyException();
    }
    return list[top];
}

template <class itemType>
StackType<itemType>::~StackType()
{
    delete [] list;
}

///////////////////////////////////////
// sample main.cpp

#include <iostream>
int main(void)
{
    try
    {
        StackType<int> stack(5);
        stack.Push(5);
        stack.Push(2);
        stack.Push(3);
        stack.Push(4);
        stack.Push(1);//<-----Still Ok!
        stack.Push(0);//<-----throw FullStack
    } catch (const StackException& e)
    {
        std::cerr << "Received a StackException: what()? " << e.what() << std::endl;
    }
}

Here is fixed a version as a single file:

See it live here: https://ideone.com/95gMc

In short:

  • you needed to define the exeption classes before you can throw them. Include them in the header file for StackType
  • do NOT use (global) using namespace in header files! You will make life miserable for users of your class that try to avoid clashes between namespaces
  • you needed to push 1 more value onto the stack

I 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

     #include <stdexcept>
    
     struct StackException : virtual std::exception 
     {  
         protected: StackException() {}
     };
     struct StackFullException : StackException 
     {
         char const* what() const throw() { return "StackFullException"; }
     };
     struct StackEmptyException : StackException
     {
         char const* what() const throw() { return "StackEmptyException"; }
     };
    

    that way you can always catch any StackException& (by reference) and handle either stack full/empty in one go

  • to handle the exception, use something like this:

    int main()
    {
         try {
               // ....
         } catch (const StackException& e)
         {
             std::cerr << "oops, a stack error occured: " << e.what() << std::endl;
         }
    } 
    

Edit example edited to demonstrate the enhanced exception types and a sample handler:

//Purpose: Header file for StackType. Containing all declerations and prototypes
#include <stdexcept>

struct StackException : virtual std::exception 
{  
    protected: StackException() {}
};
struct StackFullException : StackException 
{
    char const* what() const throw() { return "StackFullException"; }
};
struct StackEmptyException : StackException
{
    char const* what() const throw() { return "StackEmptyException"; }
};


template <class itemType>
class StackType
{
public:
    StackType   (int max);
    StackType   ();
    bool IsEmpty() const;
    bool IsFull () const;
    void Push   (itemType newItem);
    void Pop    ();
    itemType Top() const;
    ~StackType  (); // Destructor

private:
    int top;        // key:top of the stack
    int maxStack;   // max number of stack items
    itemType* list; // pointer to dynamically allocated memory
};

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*Implementation (StackStype.cpp)
StackType prototype functions*/

template <class itemType>
StackType<itemType>::StackType(int max)
{
    maxStack = max;
    top = -1;
    list = new itemType[maxStack];
}

template <class itemType>
StackType<itemType>::StackType()
{
    maxStack = 200;
    top = -1;
    list = new itemType[maxStack];
}

template <class itemType>
bool StackType<itemType>::IsEmpty() const
{
    return(top == -1);
}

template <class itemType>
bool StackType<itemType>::IsFull() const
{
    return(top == maxStack - 1);
}

template <class itemType>
void StackType<itemType>::Push(itemType newItem)
{
    if(IsFull())
    {
        throw StackFullException();
    }
    top++;
    list[top] = newItem;
}

template <class itemType>
void StackType<itemType>::Pop()
{
    if(IsEmpty())
    {
        throw StackEmptyException();
    }
    top--;
}

template <class itemType>
itemType StackType<itemType>::Top() const
{
    if(IsEmpty())
    {
        throw StackEmptyException();
    }
    return list[top];
}

template <class itemType>
StackType<itemType>::~StackType()
{
    delete [] list;
}

///////////////////////////////////////
// sample main.cpp

#include <iostream>
int main(void)
{
    try
    {
        StackType<int> stack(5);
        stack.Push(5);
        stack.Push(2);
        stack.Push(3);
        stack.Push(4);
        stack.Push(1);//<-----Still Ok!
        stack.Push(0);//<-----throw FullStack
    } catch (const StackException& e)
    {
        std::cerr << "Received a StackException: what()? " << e.what() << std::endl;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文