Throwable类是异常的根,它包含了Error与Exception,Error与Exception的区别在于:Error类一般是指与虚拟机相关的问题,如系统崩溃,虚拟机错误,内存不足等程序员无法解决的问题;而Exception是程序在运行过程中出现的问题,它是程序可以处理的异常,可以捕获且可能恢复,遇到这样的异常应该尽可能的处理它,使程序恢复正常的运行。
Exception分为运行时异常(非检查异常)与受检查异常,检查异常在程序的编译期就会检查,需要程序员在编译期做出处理,一般抛出(throw)或者用try catch语句处理。
其中,try catch语句将可能会发生异常的代码放在try语句块中,用catch语句对异常进行捕获(若不确定异常可用Exception捕获),如下:
package tryandcatch;
public class Demo {
public static void main(String[] args) {
try {
int[] a = new int[3];
for (int i = 0; i <= 4; i++) {
System.out.println(a[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {//捕获异常
System.out.println("数组下标越界");
}
}
}
throw为手动抛出异常,语法为 throw 异常对象,如:
package tryandcatch;
public class Demo {
@SuppressWarnings("unused")
public static void main(String[] args) {
try {
int[] a = new int[3];
for (int i = 0; i < 4; i++) {
System.out.println(a[i]);
throw new ArrayIndexOutOfBoundsException("数组下标越界");//抛出数组异常并自定义异常信息
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());//捕获抛出的异常
}
}
}
还可以在try catch语句之后加上finally语句块,可以关闭对象并且释放资源;需要注意的是,finall语句无论是否发生异常总会执行,如:
package tryandcatch;
public class Demo1 {
public static void main(String[] args) {
try {
int[] a = new int[3];
for (int i = 0; i <= 4; i++) {
System.out.println(a[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界");
} finally {
System.out.println("程序结束");
}
}
}
此外,还可以声明方法(throws)抛出异常,当方法本身不愿意或者不知道处理某个可能抛出的异常时可以用throws关键字将该异常提交给调用该方法的方法进行处理:
package tryandcatch;
public class Demo {
public static void main(String[] args) {
try {
way();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界");
} finally {
System.out.println("程序结束");
}
}
public static void way() throws ArrayIndexOutOfBoundsException {//声明可能抛出的异常
int[] a = new int[3];
for (int i = 0; i <= 4; i++) {
System.out.println(a[i]);
}
}
}
关于try catch finally return执行顺序问题的总结:
1、不管异常发不发生,finally语句总是执行
2、当try与catch语句中都有return语句时,finally语句依然执行
3、如果try中的语句发生异常,这个语句之后的代码就不会执行,所以一般return在finally或者catch语句中,如果只在catch中有return,则返回catch中的返回值;如果catch与finally语句中都有return,则只返回finally中的return(finally语句中的语句将替换掉catch中的return)
4、无论程序有没有发生异常,finally语句都会执行;在程序没有发生异常时,如果try与finally语句中都有return,因为finally最后执行,所以finally语句中的return将替换掉try语句中的return
5、如果try语句块发生异常,会导致 try语句块中的return 不能得到执行,所以catch或者finally中必须有一个return(一般在catch中提供)
常见的运行时异常(Runtime Exception):
1、IndexOutOfBoundsException:下标越界异常
2、NullPointerException:空指针异常
3、ClassCastException:类型转换异常
4、ArrayStoreException:xian:数组对象异常
5、ArithmeticException:算术异常