尝试向 Queue 类添加异常

尝试向 queue 类添加异常

练习文件:
queuefullexception.java
queueemptyexception.java
固定队列.java
qexcdemo.java

在这个项目中,为队列类(queue)创建了两个自定义异常,分别指示满队列和空队列的错误情况。这些异常由 put() 和 get() 方法使用。

队列异常:

queuefullexception:尝试将元素插入完整队列时抛出异常。该类包含一个用于存储最大队列大小的字段,并重写 tostring() 方法以显示自定义消息。queueemptyexception:尝试从空队列中删除元素时抛出异常。该类还重写 tostring() 以在队列为空时显示消息。

fixedqueue 类实现:

Reclaim.ai Reclaim.ai

为优先事项创建完美的时间表

Reclaim.ai 90 查看详情 Reclaim.ai fixedqueue 类已修改为在发生错误情况时抛出 queuefullexception 和 queueemptyexception。为此,put() 和 get() 在其签名中包含一个 throws 子句。通过抛出异常,您可以让调用代码更有效地处理错误。

异常和fixedqueue类代码:
queuefullexception.java

public class queuefullexception extends exception {  int size;  queuefullexception(int s) { size = s; }  public string tostring() {    return "\nqueue is full. maximum size is " + size;  }}

queueemptyexception.java:

public class queueemptyexception extends exception {  public string tostring() {    return "\nqueue is empty.";  }}

fixedqueue.java:

class fixedqueue implements icharq {  private char q[];  private int putloc, getloc;  public fixedqueue(int size) {    q = new char[size];    putloc = getloc = 0;  }  public void put(char ch) throws queuefullexception {    if (putloc == q.length)      throw new queuefullexception(q.length);    q[putloc++] = ch;  }  public char get() throws queueemptyexception {    if (getloc == putloc)      throw new queueemptyexception();    return q[getloc++];  }}

使用 qexcdemo 进行测试:
qexcdemo类模拟队列的使用:
插入元素直到超过限制,抛出 queuefullexception。
它尝试通过抛出 queueemptyexception 从空队列中删除元素。

class qexcdemo {  public static void main(string args[]) {    fixedqueue q = new fixedqueue(10);    char ch;    int i;    try {      for(i=0; i < 11; i++) {        system.out.print("attempting to store : " + (char) ('a' + i));        q.put((char) ('a' + i));        system.out.println(" - ok");      }    } catch (queuefullexception exc) {      system.out.println(exc);    }    try {      for(i=0; i < 11; i++) {        system.out.print("getting next char: ");        ch = q.get();        system.out.println(ch);      }    } catch (queueemptyexception exc) {      system.out.println(exc);    }  }}

更新了 icharq 界面:
icharq 现在在 put() 和 get() 方法中包含抛出异常,反映了固定队列抛出的异常。

public interface ICharQ {  void put(char ch) throws QueueFullException;  char get() throws QueueEmptyException;}

预期输出:
程序会显示指示元素插入和删除成功的消息,以及错误消息:
队列已满。当队列已满时,最大大小为 10。
队列为空。当尝试从空队列中删除元素时。

以上就是尝试向 Queue 类添加异常的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1006924.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
css选择器:last-of-type与nth-of-type区别
上一篇 2025年12月1日 23:36:09
sql中连接符的用法
下一篇 2025年12月1日 23:36:10

相关推荐

发表回复

登录后才能评论
关注微信