Java 使用异常来提供一致的错误处理机制,使用异常是保证代码健壮的强有力方式。
一.Java 异常体系结构
Error 是由于机器或外部原因导致的错误,比如OutOfMemoryError,这种错误是无法处理的,一般遇到这样的错误,当前线程就会终止;Exception是一种异常,是可以被处理的,java的异常处理机制就是处理Exception的。
而Exception 有分为,运行时异常和非运行时异常,亦称之为,不检查异常和检查异常,可以这样理解,运行时异常是程序运行过程中可能发生的异常,也有可能不发生,所有不需要去检查或处理它,有虚拟机帮我们处理;而非运行时异常可以理解成非常明显的异常,必须给它做处理,要不然不会编译通过,所以这类异常称之为检查异常。
二.异常的处理
Java通过5个关键字来对异常进行处理,分别是:try、catch、finally、throw、throws。
相信大家都很熟悉了,简单介绍下:
try表示可能出现异常的地方;
catch发生异常后,对异常进行处理的地方;
finally则提供了一个公共的出口,表示不管是否发生异常都会执行;
throw用来在方法体内部抛出一个异常;
throws是说如果当前方法没有能力处理该异常,则用它来声明该方法可能抛出的异常,然后交给调用者去处理它所抛出的异常;如果把异常一直往上抛不做处理,如果抛到main()后,程序将退出,如果是线程,则线程退出。
三.异常处理案例
该案例,在一些面试题上面看到过,其实只需注意一点,try{...}catch{...}finally{...}是一个整体,无论return 还是throw 都需在这个整体执行完后,才做相应的renturn或throw。
public class 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