Exception之循环是否继续?

一、问题说明

当一个for循环的中如果抛出Exception时,那么异常之后的循环是否继续进行呢?

二、示例代码

package com.wbf.test;

public class ExceptionDemo {

	public static void fun(){
		for (int i = 0 ;i < 10; i++)
		{
			if (i == 3)
			{
				int j = i/0;
			}
			else
			{
				System.out.println(i);
			}
			/*try {
				if (i == 3)
				{
					int j = i/0;
				}
				else
				{
					System.out.println(i);
				}
			} catch(Exception e){
				e.printStackTrace();
				//continue;
			}*/
		}
	}
}
import com.wbf.test.ExceptionDemo;

import junit.framework.TestCase;

public class ExceptionTest extends TestCase {

	public void testFun(){
		ExceptionDemo ed = new ExceptionDemo();
		ed.fun();
	}
}
如果没有try...catch,那么在i == 3时候,代码抛出异常,那么i从4至9的流程是不会执行的,但是如果加上异常处理,那么只是在i == 3时候抛出异常,之后的流程会继续执行
以下是两种不同情况的运行结果:

0
1
2

-----------------------------------------------------------

0
1
2
java.lang.ArithmeticException: / by zero
at com.wbf.test.ExceptionDemo.fun(ExceptionDemo.java:11)
at ExceptionTest.testFun(ExceptionTest.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:164)
at junit.framework.TestCase.runBare(TestCase.java:130)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
4
5
6
7
8
9

----------------------------------------------------------

三、说明

在有try...catch异常处理的时候,即使i == 3的时候抛出异常,但是在catch部分还是将当前这一流程走完了,所以循环可以往下走,好比多了一条路,但是如果没有catch异常处

理,就好比只有一条路,此时又阻塞了,所以循环不能往下执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值