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());

解决方案 »

  1.   

    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;
    }

    }
      

  2.   

    throws Exception 
      这两句不写 chatClients.remove(key);
    continue;
    试试看
      

  3.   

    chatClients.remove(key);
    这个也许throw out runtime exception.
    具体要调试一下.
      

  4.   

    我觉得应该是先确认以下变量it里面有几个内容。
    有可能是抛出异常后,运行到continue语句,会继续执行循环,
    但是it.hasNext()为false,当然就结束循环了啊。
      

  5.   

    把上面的循环改成
    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中已经没有下一个元素了。