不懂得处理异常你是敢说你是学Java

通过前面的章节,我们深刻的理解了Java中方法、属性、引用、关键字之间的联系,回顾:

一个“方法”带来的诸多问题

一个变量带来的深层思考

来讲讲Java中“引用”这两个字

我们平常使用“关键字”容易忽略的那些点

但是明白了这些后,我们平常在写程序的时候可能会出现一些我们不想要的Exception—异常。

我们常常说的异常是Exception,而不是error,error指运行环境出现的错误,是程序检测不出来的,属于系统的内部(例如JVM)错误。

例如资源不够会出现OutOfMemoryError/StackOverflowError一样,这类错误不该是让程序去控制的,出现此类错误一般都是程序设计的问题。

#Exception

可以通过捕捉处理使程序继续执行,是程序自身可以处理的异常。

不扯太多废话,直接看一段代码:摘自

public class TestException {
	public TestException() {}
 
	boolean testEx() throws Exception {
		boolean ret = true;
		try {
			ret = testEx1();
		} catch (Exception e) {
			System.out.println("testEx, catch exception");
			ret = false;
			throw e;
		} finally {
			System.out.println("testEx, finally; return value=" + ret);
			return ret;
		}
	}
 
	boolean testEx1() throws Exception {
		boolean ret = true;
		try {
			ret = testEx2();
			if (!ret) {
				return false;
			}
			System.out.println("testEx1, at the end of try");
			return ret;
		} catch (Exception e) {
			System.out.println("testEx1, catch exception");
			ret = false;
			throw e;
		} finally {
			System.out.println("testEx1, finally; return value=" + ret);
			return ret;
		}
	}
 
	boolean testEx2() throws Exception {
		boolean ret = true;
		try {
			int b = 12;
			int c;
			for (int i = 2; i >= -2; i--) {
				c = b / i;
				System.out.println("i=" + i);
			}
			return true;
		} catch (Exception e) {
			System.out.println("testEx2, catch exception");
			ret = false;
			throw e;
		} finally {
			System.out.println("testEx2, finally; return value=" + ret);
			return ret;
		}
	}
 
	public static void main(String[] args) {
		TestException testException1 = new TestException();
		try {
			testException1.testEx();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

运行结果:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

你做对了吗?

对于异常的详细讲解,这里直接推荐一篇不错的文章:
深入理解java异常处理机制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值