第8章 异常处理(4)

异常的定义

运行期出现的错误

异常的继承图

image.png

Object 类的直接子类Throwable描述了所有被虚拟机抛出的非正常状况。一般情况下很少用Throwable,而是使用它的两个子类Error、Exception。

Error类特指应用程序在运行期间发生的严重错误。如:虚拟机内存用尽、堆栈溢出等等。一般情况下这种错误都是灾难性的,所以没有必要使用异常处理机制处理Error。

Exception类有几十个子类,描述了不同类型的异常,其中:

以RuntimeException为代表的一些类,称为非检查性异常(unchecked Exception),

以IOException为代表的一些类为检查性异常(checked Exception)。所谓的检查和非检查是指编译器在编译时是否检查。如果代码中存在检查性异常,必须进行异常处理,否则编译时不能通过;而非检查性异常编译时不进行检查,到运行时才会显现。

异常类型

检查性异常(checked exception)

若系统运行时可能产生该类异常,则必须写出相应的处理代码,否则无法通过编译

非RuntimeException异常

非检查性异常(unchecked exception)

若系统运行时可能产生该类异常,则不必在程序中声明对该类异常的处理,就可以编译执行

RuntimeException:运行时异常

注意:我们主要学习检查性异常的处理

非检查性异常

RuntimeException    运行期异常

ArithmeticException 运算错误

IllegalArgumentException  参数错误

ArrayIndexOutOfBoundsException 数组越界

NullPointerException 空指针

检查性异常

IOException  输入输出错误,是下面检查性异常的父类

ClassNotFoundException  类不存在

FileNotFoundException  文件不存在

EOFException            文件结束异常

IllegalAccessException  对类的访问被拒绝

NoSuchMethodException  没有这个方法

InterruptedException    多线程异常,线程中断

异常的处理两种方式

第一种 try{有可能会出现异常的代码...}catch{一旦捕获着了,如何处理..}

@Testpublicvoidtest(){//检查性异常( 编译期异常)try{FileInputStreamfile=newFileInputStream("E:/java16/javase/test1.txt");}catch(FileNotFoundExceptione){// TODO Auto-generated catch blocke.printStackTrace();}}

第二种 throws ***Exception 向上层抛弃,也就是抛给调用方法的人

通常:如果是数据库级别的,我们要处理,如果是其他异常,底层向上抛,上层处理

@Testpublicvoidtest()throwsFileNotFoundException{//检查性异常( 编译期异常)FileInputStreamfile=newFileInputStream("E:/java16/javase/test1.txt");}

注意:捕获时,子类的异常放在里层,父类的异常放在外层,即从小往大捕获

@Testpublicvoidtest(){// Exception和FileNotFoundException不能写颠倒,小的放在里层,大的放在最外层//检查性异常( 编译期异常)try{Strings[]={"1","2","3"};inti=0;System.out.println(s[4]);FileInputStreamfile=newFileInputStream("E:/java16/javase/test1.txt");}catch(FileNotFoundExceptione){e.printStackTrace();System.out.println("文件没有找到");}catch(Exceptione){e.printStackTrace();System.out.println("出现异常"+e.getMessage());}}

Catch多个异常的写法

分别处理

@Testpublicvoidtest(){intnum[]={1,2,3};try{for(inti=0;i<num.length;i++){System.out.println("请输入除数");Scannersc=newScanner(System.in);intinput=sc.nextInt();System.out.println(num[i]/input);}}catch(ArithmeticExceptione){//e.printStackTrace();System.out.println("被0除了");}catch(InputMismatchExceptione1){//e1.printStackTrace();System.out.println("请输入整数");}catch(Exceptione2){//e1.printStackTrace();System.out.println("未知异常");}}

合并处理(jdk1.7之后)Exception3.java

@Testpublicvoidtest1(){intnum[]={1,2,3};try{for(inti=0;i<num.length;i++){System.out.println("请输入除数");Scannersc=newScanner(System.in);intinput=sc.nextInt();System.out.println(num[i]/input);}}catch(ArithmeticException|InputMismatchExceptione){//jdk1.7之后新增的写法System.out.println("输入错误");}}

finally块Exception4.java

try---finally

try--catch--finally

@Testpublicvoidtest1(){intnum[]={1,2,3};Scannersc=newScanner(System.in);try{for(inti=0;i<num.length;i++){System.out.println("请输入除数");intinput=sc.nextInt();System.out.println(num[i]/input);}}catch(ArithmeticException|InputMismatchExceptione){// jdk1.7之后新增的写法System.out.println("输入错误");}finally{//后处理块 清理缓存和关闭连接 正常情况他都会执行//try-finally  程序没有出现异常//try-catch-finally  程序出现了异常sc.close();System.out.println("我是finally");}}

System.exit(0) finally代码块中的内容不被执行

@Testpublicvoidtest1(){intnum[]={1,2,3};Scannersc=newScanner(System.in);try{for(inti=0;i<num.length;i++){System.out.println("请输入除数");intinput=sc.nextInt();System.out.println(num[i]/input);}}catch(ArithmeticException|InputMismatchExceptione){// jdk1.7之后新增的写法System.out.println("输入错误");//强制退出,不执行finallySystem.exit(0);}finally{//后处理块 清理缓存和关闭连接 正常情况他都会执行//try-finally  程序没有出现异常//try-catch-finally  程序出现了异常sc.close();System.out.println("我是finally");}}

自定义异常 AppException  BusinessException  DbException

/**

* 自定义异常,继承Exception

* @author Administrator

*

*/publicclassAppExceptionextendsException{privatestaticfinallongserialVersionUID=-3772114394224548773L;privateStringcode;/**

    *

    * @param code  999-未知异常  0-成功 100-用户名错误  101-密码错误

    * @param message

    */publicAppException(Stringcode,Stringmessage){super(message);this.code=code;}publicStringgetCode(){returncode;}}publicclassBusinessExceptionextendsException{privatestaticfinallongserialVersionUID=6815756811652789347L;privateStringcode;publicBusinessException(Stringcode,Stringmessage){super(message);this.code=code;}publicStringgetCode(){returncode;}}publicclassDbExceptionextendsException{privatestaticfinallongserialVersionUID=-6395430404968261254L;privateStringcode;publicDbException(Stringcode,Stringmessage){super(message);this.code=code;}publicStringgetCode(){returncode;}}

throw 抛出自定义异常CatchMultiException.java

底层向上抛:

publicstaticvoidtest(inta)throwsAppException,BusinessException,DbException{if(a==0){thrownewAppException("0","应用程序异常");// 抛出第一个异常}if(a==1){thrownewBusinessException("2","异常2");// 抛出第二个异常}if(a==2){thrownewDbException("3","异常3");// 抛出第三个异常}}

上层的方法要对异常进行处理

处理方式

1)继续向上抛

publicstaticvoidmain(String[]args)throwsAppException,BusinessException,DbException{test(0);}

2)surrount width try-catch 各个异常分别处理

publicstaticvoidmain(String[]args){try{test(0);}catch(AppException e){// TODO Auto-generated catch blocke.printStackTrace();}catch(BusinessException e){// TODO Auto-generated catch blocke.printStackTrace();}catch(DbException e){// TODO Auto-generated catch blocke.printStackTrace();}}

3) surrount width muilti-catch 各个异常合并处理

publicstaticvoidmain(String[]args){try{test(0);}catch(AppException|BusinessException|DbException e){// TODO Auto-generated catch blocke.printStackTrace();}}

调用堆栈:后进先出Exception5.java

publicclassException6{int[]arr=newint[3];publicstaticvoidmain(String[]args){try{newException6().methodOne();System.out.println("main");}catch(AppExceptione){// TODO Auto-generated catch blocke.printStackTrace();System.out.println("程序异常");}}publicvoidmethodOne()throws AppException{methodTwo();System.out.println("One");}publicvoidmethodTwo()throws AppException{methodThree();System.out.println("Two");}publicvoidmethodThree()throws AppException{try{System.out.println(arr[3]);System.out.println("Three");}catch(Exceptione){thrownewAppException("999","未知异常");}}}

跟异常相关的关键词

try{}

catch{}

finally{}

System.exit(0);

throws

throw new ***Exception

线上学习

文件与流

转至:↓↓↓

链接:https://www.jianshu.com/p/0a08c999693c

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。