※ 为什么循环不能继续?

J_2004 2006-05-31 10:53:13
while (it.hasNext()){
key = it.next();
try{
cc = (ChatClient)chatClients.get(key);
cc.sendln(str);
}catch(Exception e){
//e.printStackTrace();
try {
cc.close();
} catch (Exception e1) {
e1.printStackTrace();

}
chatClients.remove(key);
continue;
}

}

---------
运行以上代码,当发生异常时,循环就退出了。已经捕获异常,并处理了,为什么循环不能继续?
*异常是这个方法抛出的: cc.sendln(str) -> writer.write(s);writer是用socket输出流构造的OutputStreamWriter对象;writer = new OutputStreamWriter(socket.getOutputStream());

...全文
182 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
J_2004 2006-05-31
  • 打赏
  • 举报
回复
楼上的不行
顶!!!!!!!
crazyxp 2006-05-31
  • 打赏
  • 举报
回复
while (it.hasNext()){
key = it.next();
try{
cc = (ChatClient)chatClients.get(key);
cc.sendln(str);
}catch(Exception e){
//e.printStackTrace();
continue;
try {
cc.close();
} catch (Exception e1) {
e1.printStackTrace();

}
chatClients.remove(key);
continue;
}

}
afrag 2006-05-31
  • 打赏
  • 举报
回复
把上面的循环改成
while (true){
if (it.hasNext() == false)
{
System.out.println("it has not next element");
break;
}
key = it.next();
try{
cc = (ChatClient)chatClients.get(key);
cc.sendln(str);
}catch(Exception e){
//e.printStackTrace();
try {
cc.close();
} catch (Exception e1) {
e1.printStackTrace();

}
chatClients.remove(key);
continue;
}

}
这样来检验一下退出循环到底是因为异常还是因为Iterator中已经没有下一个元素了。
afrag 2006-05-31
  • 打赏
  • 举报
回复
我觉得应该是先确认以下变量it里面有几个内容。
有可能是抛出异常后,运行到continue语句,会继续执行循环,
但是it.hasNext()为false,当然就结束循环了啊。
wangsheng1028 2006-05-31
  • 打赏
  • 举报
回复
chatClients.remove(key);
这个也许throw out runtime exception.
具体要调试一下.
treeroot 2006-05-31
  • 打赏
  • 举报
回复
kingofworl 2006-05-31
  • 打赏
  • 举报
回复
throws Exception
这两句不写 chatClients.remove(key);
continue;
试试看

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧