异常概念
所谓异常就是程序中出现了问题。异常可以作为方法内的一种特殊返回值,以便上层调用者知道底层的执行情况。
Error:程序无法处理的错误,例如虚拟机内存不够(OOM)
Exception:程序可以处理的错误,可以分为运行时异常和编译时异常
运行时异常:RuntimeException及其子类,编译阶段不会出现错误提醒,运行时出现的异常。例如:NullPointerException、NumberFormatException、ArrayIndexOutOfBoundsException、IllegalArgumentException。
编译时异常:编译阶段就会出现错误提醒。例如:ClassNotFoundException、SQLException。
异常处理方法
抛出异常(throws)
在方法上使用throws关键字,将方法内部出现的异常抛出给调用者处理。
public class MessageSourceValidator throws Exception{
......
}
捕获异常(try…catch)
直接捕获程序出现的异常。
try {
throw new RuntimeException("RuntimeException");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("hh");
}
无论是否捕获或处理异常,finally 块里的语句都会被执行。当在 try 块或 catch 块中遇到 return 语句时,finally 语句块将在方法返回之前被执行。