通过前面的章节,我们深刻的理解了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异常处理机制。