目录
异常分类
编译时异常
运行时异常
常见:ClassCastException,NullPointException,OutofIndexBoundsException,ArithmeticException等等
catch() 语句块在 JDK1.7 的新特性
支持多个异常类型,用 | 连接。
try{
...
}catch (ArithmeticException | NumberFormatException n) {
n.printStackTrace();
}
try{}catch(){}finally{}语句块中的 return 语句
try{}中有 return(try中无异常发生)
private static int exceptionTest() { int a = 55; try { a = 500; return a; } catch (Exception e) { e.printStackTrace(); } return a; } // 输出结果:500
try{}中有 return(try中有异常发生)
private static int exceptionTest() { int a = 55; try { a = 500 / 0; return a; } catch (Exception e) { e.printStackTrace(); } return a; } // 输出结果:55
catch(){} 中有 return
private static int exceptionTest() { int a = 55; try { a = 500 / 0; return a; } catch (Exception e) { a = 5; return a; // e.printStackTrace(); } // return a; } // 输出结果:5
之所以注释掉这里最后的 return,是因为 try 和 catch 中必定有一个return 会执行到,所以最后的 return 是执行不到的。下面看看加上 finally 的几种情况:
try{} 无异常带上 finally 的情况
private static int exceptionTest() { int a = 55; try { a = 500 / 10; return a; } catch (Exception e) { a = 5; return a; // e.printStackTrace(); } finally { a = 100; System.out.println("finally-->" + a); } // return a; } // 输出结果: finally-->100 50
结果分析:即使 try{} 中有 return 语句,但是如果有 finally{} 语句块,还是会执行 finally{} 中的代码。
try{} 有异常带上 finally 的情况
private static int exceptionTest() { int a = 55; try { a = 500 / 0; return a; } catch (Exception e) { a = 5; return a; // e.printStackTrace(); } finally { a = 100; System.out.println("finally-->" + a); } // return a; } // 输出结果: finally-->100 5
结果:只要带了 finally{} 语句块,那么这里面的代码是一定会执行的,之所以没有改变变量的值,那是因为,之前的 return 语句已经“做好了执行的准备”,也就是说变量的值已经被“包装好了”,只在等待输出而已。而 finally{} 的代码块之所以被执行,这和它的功能有很大的关系,finally{} 语句块的功能是用来释放资源的,比如:关闭 IO 流、数据库等。
面试题:final 、finally 和 finalize 的区别
final
:是修饰符。修饰类,那么该类不能被继承;修饰方法,那么该方法不能被重写;修饰变量,那么该变量时常量。
finally
:是异常处理中肯定会执行到的语句块,用来释放资源。
finalize
:finalize()是 Object 中的方法,当垃圾回收器将要回收对象所占内存之前被调用,即当一个对象被虚拟机宣告死亡时会先调用它finalize()方法,让此对象处理它生前的最后事情(这个对象可以趁这个时机挣脱死亡的命运)。