6. 异常处理
6.1 异常概述与异常体系结构
- 在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如: 客户输入数据的格式, 读取文件是否存在, 网络是否始终保持通畅等等
- 异常:在Java语言中, 将程序执行中发生的不正常情况称为“异常” (开发过程中的语法错误和逻辑错误不是异常)
- 异常可以分为两类:
- Error: Java虚拟机无法解决的严重问题。 如: JVM系统内部错误、 资源耗尽等严重情况。 比如:栈溢出StackOverflowError和堆溢出OutOfMemoryError,一般不编写针对性的代码进行处理
- Exception: 其它因编程错误或偶然的外在因素导致的一般性问题, 可以使用针对性的代码进行处理,例如:(不一定出现,以防万一)
- 空指针访问
- 试图读取不存在的文件
- 网络连接中断
- 数组角标越界
- 两种解决方法:
- 遇到错误就终止程序的运行
- 由程序员在编写程序时,就考虑到错位的检测、错误消息的提示,以及错误的处理
- 捕获错误最理想的是在编译期间, 但有的错误只有在运行时才会发生。比如: 除数为0, 数组下标越界等,故分类为: 编译时异常和运行时异常
- 异常的体系结构:
- java.lang.Throwable
- java.lang.Error:一般不编写针对性的代码进行处理
- java.lang.Exception:可以进行异常的处理
- 编译时异常(checked)
- IOException
- FileNotFoundException
- ClassNotFoundException
- IOException
- 运行时异常(unchecked)
- NullPointerExceptionkon空指针
- ArrayIndexOutOfBoundsException位越界
- ClassCastException
- NumberFormatException
- InputMisamatchException输入不匹配
- ArithmaticException算数异常
- 编译时异常(checked)
- java.lang.Throwable
6.2 常见异常
-
运行时异常:
-
NullPointerException
public void test1() { int[] arr = null; System.out.println(arr[3]); }
-
ArrayIndexOutOfBoundsException
public void test1() { int[] arr = {1,2,3}; System.out.println(arr[3]); }
-
StringIndexOutOfBoundsException
public void test1() { String str = "abc"; System.out.println(str.charAt(3)); }
-
ClassCastException
public void test1() { Object O = new Date(); String str = (String) O;//类型转换异常 }
-
NumberFormatException
public void test1() { String str = "abc"; int num = Integer.parseInt(str); }
-
InputMisamatchException
public void test1() { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt();//输入一个a时 System.out.println(num); }
-
ArithmeticException
public void test1() { int a = 10; int b = 0; System.out.println(a/b); }
-
-
编译时异常:
编译代码时就会报错
6.3 异常处理机制一:try-catch-finally
-
异常处理概述:抓抛模型
-
抛:程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象,并将此对象抛出,一旦抛出异常后,其后的代码不再执行
-
抓:可以理解为异常的处理方式
- try-catch-finally
- throws+异常类型
-
-
try-catch-finally处理方式(IDEA快捷键ctrl+alt+t)
-
格式:
try{ //可能出现异常的代码 }catch(异常类型1 变量名1){ //处理异常的方式1 }catch(异常类型2 变量名2){ //处理异常的方式2 }catch(异常类型3 变量名3){ //处理异常的方式3 } ... finally{ //一定会执行的代码 }
-
说明:
- finally是可选的
- 使用try将可能出现的异常包装起来,在执行的过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,取catch中进行匹配
- 一旦try中的异常匹配到一个catch,就进入catch中进行异常的处理
- 处理完成就跳出try-catch结构(没有写finally的情况下)
- catch中的异常没有子父类关系,则谁声明的前后顺序无所谓;若catch中的异常有子父类关系,要求子类一定在父类的上面,否则报错
- 在try结构中定义的变量,则出来try结构则不能调用
- try-catch结构可以相互嵌套
-
示例:
public class ExceptionTest { public static void main(String[] args) { int[] arr = null; try{ int num;//见下 System.out.println(arr[3]); System.out.println("11111");//不会执行 }catch (NullPointerException e){ System.out.println("出现空指针异常"); //方式1 System.out.println(e.getMessage()); //方式2 e.printStackTrace(); }catch (Exception e){//父类异常要写在子类后边 System.out.println("出现异常"); } //System.out.println(num); //Cannot resolve symbol 'num' //不能调用try结构里的num System.out.println("111111");//异常被处理了,可以执行 } }
-
-
finally的使用
-
finally中声明的语句一定会被执行,即使①catch中又出现了异常,②try中有return语句,③catch中有return语句
-
像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动回收的,我们需要自己手动的进行资源的释放,此时的资源释放,就需要声明在finally中
public class ExceptionTest { public static void main(String[] args) { FileInputStream fis = null; //为了在finally中能使用fis,故需要将fis的声明移除try结构 try { File file = new File("hello.txt"); fis = new FileInputStream(file); int data = fis.read(); while (data != -1) { System.out.println((char) data); data = fis.read(); } }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { try{ fis.close();//⭐ }catch (IOException e){ e.printStackTrace(); } } } }
-
-
开发中,由于运行时异常比较常见,所以我们通常就⭐不针对运行时异常编写try-catch-finally了
-
而针对编译时异常,我们就一定要考虑处理异常
6.4 异常处理机制一:throws+异常类型
-
throws + 异常类型
写再方法的声明处。指明此方法执行时,可能会抛出的异常类型,一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出 -
异常代码后面的代码就不会被执行了,因为在本方法内并没有被处理,而是被抛给了上层方法
-
try-catch-finally:真正的将异常给处理掉了
-
throws:只是将异常抛给了调用者,并没有真正的处理异常
-
注意:
方法重写的规则之一:子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型
-
开发中如何选择两种方式:
- 如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,必须使用try-catch-finally处理异常
- 执行的方法中,先后又调用了另外的几个方法,这几个方法时递进关系执行的,故建议将几个方法使用throws方式处理,而最高层的执行方法a可以考虑使用try-catch-finally处理
6.5 手动抛出异常:throw
-
Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出, 也可根据需要使用人工创建并抛出
-
示例:
public class ExceptionTest { public static void main(String[] args) { try { ExceptionTest exceptionTest = new ExceptionTest(); exceptionTest.regist(-1001); } catch (Exception e) { //e.printStackTrace(); System.out.println(e.getMessage()); } } int id; public void regist(int id) throws Exception{ if(id > 0){ this.id = id; }else { //太low了 //System.out.println("输入的id不合法"); //如果抛一个RuntimeException,编译不会报错,但不会处理 //throw new RuntimeException("输入的id不合法"); //如果抛一个Exception,需要抛给main方法处理异常 throw new Exception("输入的id不合法"); } } }
6.6 用户自定义异常类
-
如何自定义异常类?
- 继承于现有的异常结构:RuntimeException、Exception
- 提供全局常量:serialVersionUID(标识作用)
- 提供重载的构造器
-
示例:
public class MyException extends Exception{ private static final long serialVersionUID = 1687848808490L; public MyException() { } public MyException(String message) { super(message); } }
-
使用:
throw new MyException("输入的id不合法");