一.异常分类
Java中所有的异常类都是派生于Throwable。Java异常类层次结构图如下
Throwable下主要分解为两支:Error和Exception
- Error层次描述了java运行时系统的内部错误和资源耗尽错误。大多数错误与代码编写者执行的操作无关,而表示JVM出现的问题。应用程序不应该抛出这种类型的对象。
- Exception层次又分解为两个分支:一个分支派生于RuntimeException;另一个分支包含其他异常。划分两个分支的规则是:由程序错误导致的异常属于RuntimeException;而程序本身没有没有问题,但由于像I/O错误这类异常导致的异常属于其他异常。
常见RuntimeException(运行时异常)
- IndexOutOfBoundsException(下标越界异常)
- NullPointerException(空指针异常)
- NumberFormatException (String转换为指定的数字类型异常)
- ArithmeticException -(算术运算异常 如除数为0)
- ArrayStoreException - (向数组中存放与声明类型不兼容对象异常)
- SecurityException -(安全异常)
常见非RuntimeException(受检异常)
- FileNotFoundException(文件未找到异常)
- IOException(操作输入流和输出流时可能出现的异常)
- EOFException (文件已结束异常)
二.概念
unchecked exception(非检查异常)
包括运行时异常(RuntimeException)和继承Error类的异常。对于非检查异常,Java编译器不要求必须处理,可处理也可不处理。
checked exception(检查异常,编译异常)
Exception下排除RuntimeException所剩下的异常是检查异常,Java编译器强制要求必须进行处理,否则编译不通过。
三.异常的处理
3.1.抛出异常
- 当需要抛出异常时使用throw抛出
- 调用一个抛出检查异常的方法必须用throws声明
1 public void method() throws FileNotFoundException { 2 //一个会抛出异常的方法 3 method2(); 4 } 5 //这里 方法后是throws 6 public void method2() throws FileNotFoundException { 7 //这里是throw 8 throw new FileNotFoundException(); 9 }
3.2.捕获异常
使用try,catch,finally语句块捕获异常
1 public class TEST { 2 3 public static String t1() { 4 try { 5 System.out.println("t1 try block"); 6 return t2(); 7 } finally { 8 System.out.println("t1 finally block"); 9 } 10 } 11 public static String t2() { 12 System.out.println("t2 return statement"); 13 return "t2 return"; 14 } 15 16 public static void main(String[] args) { 17 System.out.println(t1()); 18 } 19 }
t1 try block t2 return statement t1 finally block t2 return
上面代码中try或catch中存在return,那么finally执行顺序如图所示
1 public class TEST { 2 public static void main(String[] args) { 3 System.out.println("b最后的结果:" + t()); 4 } 5 public static int t() { 6 int b = 1; 7 try { 8 System.out.println("t try block"); 9 return b += 1; 10 } catch (Exception e) { 11 System.out.println("t catch block"); 12 } finally { 13 System.out.println("t finally block"); 14 if (b > 1) { 15 System.out.println("b>1, b = " + b); 16 } 17 b = 3; 18 return b; 19 } 20 } 21 }
t try block t finally block b>1, b = 2 b最后的结果:3
上面代码中finally里有return,那么对try或catch中返回值进行修改将生效
1 public class TEST { 2 public static void main(String[] args) { 3 System.out.println("b最后的结果:" + t()); 4 } 5 6 public static int t() { 7 int b = 1; 8 try { 9 System.out.println("t try block"); 10 return b += 1; 11 } catch (Exception e) { 12 System.out.println("t catch block"); 13 return b; 14 } finally { 15 System.out.println("t finally block"); 16 if (b > 1) { 17 b = 3; 18 System.out.println("b>1, b = " + b); 19 } 20 } 21 } 22 }
t try block t finally block b>1, b = 3 b最后的结果:2
上面代码中finally里没有return,那么对try或catch中返回值修改不会生效