怎么捕获异常,让循环继续?

cclxy1984 2009-11-03 08:57:40
有个循环,我在外面捕获异常,return一个字符窜FALSE。比如我循环到第5个了,出现异常了,return了,但后面的循环还会继续吗?如果不能,怎么写catch里的语句,让循环继续?
...全文
2421 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
cclxy1984 2009-11-03
  • 打赏
  • 举报
回复
额,这样的,群发邮件,比如第5个人出错了,以前是后面都不发送了,现在想后面继续发送。循环里,方法套方法,看的我晕了。。。
末爷_ 2009-11-03
  • 打赏
  • 举报
回复
你这逻辑不对的哇,都出现异常了,肯定就会跳出循环咯,不然捕捉异常干嘛?这个是一个程序逻辑,出错就应该跳出,不再继续执行。
gjsong 2009-11-03
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 cclxy1984 的回复:]
代码比如:
for(xxxx){
  methoda();
}
在methoda()里我做了try/catch,那如果异常了,循环继续否?
[/Quote]
那要看你的methoda里面对异常怎么处理了,如果你try-catch捕获了,那么你的for循环是否会继续要看你循环里面怎么写逻辑了
但是如果你是在methoda里throw得异常for循环也会终止的
qizhe 2009-11-03
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) {
int i = 0;
String[] s = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" };
System.out.println(loop(s));

}

public static boolean loop(String[] s) {
boolean a = true;

for (int i = 0; i < s.length; i++) {
try {
if (i == 5) {
throw new Exception(i + ":这里抛出异常!");
}
System.out.println(i + ":" + s[i]);
} catch (Exception e) {
a=false;
continue;
}
}
return a;
}
结合楼上二位,呵呵。lisong526的有递归,gjsong的没有返回值。
cclxy1984 2009-11-03
  • 打赏
  • 举报
回复
对,我只想知道哪个地方错了,然后让后面的继续执行
cclxy1984 2009-11-03
  • 打赏
  • 举报
回复
代码比如:
for(xxxx){
methoda();
}
在methoda()里我做了try/catch,那如果异常了,循环继续否?
qizhe 2009-11-03
  • 打赏
  • 举报
回复
你希望出现异常时方法返回值为false,不出现异常方法返回值为true
但无论是否有异常,循环都需要执行完,是这个意思不?
gjsong 2009-11-03
  • 打赏
  • 举报
回复

public static void main(String[] args) {

method();

}

public static void method() {
for (int i = 0; i < 10; i++) {
try {

int k = 10 / i;
System.out.println(k);

} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}

gjsong 2009-11-03
  • 打赏
  • 举报
回复
出现异常了 如果你的return放在catch块里
循环应该就不会继续了,整个方法就退出了
如果要让循环继续,catch块里面用continue;
try--catch块放在循环里面
嘟嘟xo 2009-11-03
  • 打赏
  • 举报
回复

public static void main(String[] args) {
int i = 0;
String[] s = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" };
System.out.println(loop(i, s));

}

public static boolean loop(int i, String[] s) {
try {
for (int iSize = s.length; i < iSize; i++) {
if (i == 5) {
throw new Exception(i + ":这里抛出异常!");
}
System.out.println(i + ":" + s[i]);
}
} catch (Exception e) {
loop(i + 1, s);
return false;
}
return true;
}
qizhe 2009-11-03
  • 打赏
  • 举报
回复
在外面捕获异常,循环中出现异常后边的循环不会执行。如果你有return,那return后的代码也都不会执行。
把代码贴出来研究一下怎么写吧。
feiyangdesky 2009-11-03
  • 打赏
  • 举报
回复
顶了!!!!!!!!!!
ljsnake 2009-11-03
  • 打赏
  • 举报
回复
把try{}catch(Exception e){}放for循环里面啊,for要做的事情放try{}里啊:
boolean flag=true;
for(int i=0;i<10;i++){
try{
//...
}catch(Exception e){
//System.out.println(FALSE);
flag=false;
//continue;
}
}
return flag;
//不知道能否满足要求,你试下吧
//循环继续的指令是continue,循环终止跳出用break;
dyingmanliu 2009-11-03
  • 打赏
  • 举报
回复
test

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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