Error与Exception的区别
Error是程序无法处理的错误,比如OutMemoryError,ThreadDeath等,这些异常发生的时候,Java虚拟机(JVM)一般会选择线程终止。此类异常是程序猿的致命异常。
Exception是程序本身可以处理的异常,这种异常分为两大类运行时异常和非运行时异常,程序中应该尽可能去处理这种异常。
Exception类的继承关系
运行时异常和非运行时异常的区别
运行时异常都是RuntimeException类及其子类,如NullPointerException、IndexOutOfBoundsException等,这些异常一般是由程序逻辑错误引起的,程序员应当从逻辑的角度尽量避免此类异常的发生。
非运行时异常时RunTimeException以外的异常,类型上都属于Exception类及其子类。从程序语法角度讲,是必须处理的异常,如果不处理程序就不能编译通过。如IOException,SQLException等以及用户自定义的Exception异常,这些是检查型异常。一般情况下不自定义检查型异常。
内置异常类(积累ing)
非检查性异常
异常 | 描述 |
---|---|
检查性异常
异常 | 描述 |
---|---|
内置异常方法(积累ing)
方法 | 说明 |
---|---|
捕获异常
package org.example;
import java.util.*;
public class Main {
public static void foo(){
int[] array = new int[5];
for (int i = 0; i < array.length; i ++){
array[i]= i;//初始化数组
}
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int x = sc.nextInt();
try{
array[k] /= x;
}catch (ArithmeticException e){
System.out.println("除以零啦!");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("数组越界啦!");
}finally {
//不管有没有异常都会执行的代码
for(int i = 0; i < 5; i ++){
System.out.printf("array[%d] = %d\n",i,array[i]);
}
}
}
public static void main(String[] args) {
foo();
}
}
/*
输出结果:
-1 0
数组越界啦!
array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
3 0
除以零啦!
array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
*/
抛出异常(没学明白~~)
throw:在函数内抛出一个异常
throws:在函数定义时抛出一些可能的异常
检查型异常必须被捕获或者抛出(这是两种处理异常的方法)
package org.example;
import java.io.IOException;
import java.util.*;
public class Main {
private static void foo(){
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
if(x == 1){
try {
throw new IOException("找不到文件!!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
foo();
}
}
/*
输出结果
1
找不到文件!!
*/
try-with-resources(也没听懂~~)
jdk7之后,java新增的try-with-resources语法糖用来打开资源,并且可以确保在语句执行完之后关闭所有资源。
try用来申明和实例化资源,catch用来处理关闭资源所引发的异常。