Java异常类型及处理前言:异常是指程序执行过程中出现异常情况,导致javajvm停止运行。异常结构为:Throwable是顶级父类,子类Error是严重错误报告。子类Exception就是我们所说的异常。异常处理的关键字java中处理异常的关键字有五个:try,catch,finally,throw,throwsthrow抛出异常,thorws声明异常,捕获异常try_catchthrowpublicclassSegmentFault{publicstaticvoidmain(String[]args){/***throw抛出异常*格式-thrownew异常类名(参数);**///创建数组int[]arr={2,4,56,5};//根据索引找到对应的元素intindex=4;intelement=getElement(arr,index);System.out.println(元素);System.out.println("owo");//运行错误无法继续}/**throw抛出异常提醒必须处理*/publicstaticintgetElement(int[]arr,intindex){//判断数组索引是否越界if(index<0||index>arr.length-1){/***条件满足,出界。当执行到throw抛出异常时,无法运行,方法结束提示**/thrownewArrayIndexOutOfBoundsException("Arraysubscriptoutofboundsexception");}int元素=arr[索引];返回元素;}}异常结果为:Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:数组索引越界异常抛出,IOException{if(!path.equals("a.txt")){//如果没有a.txt//如果不是a.txt,则报文件不存在的错误,即,抛出异常thrownewFileNotFoundException("文件不存在");}if(!path.equals("b.txt")){thrownewIOException("文件不存在");}}}异常结果为:Exceptioninthread"main"java.io.IOException:Thefiledoesnotexisttry,catch,finally+Throwable中有常用的方法Throwable常用的方法如下printStackTrace():*打印详细信息getMessage():获取异常的原因toString():获取异常的类型和描述。publicclassDemo03{publicstaticvoidmain(String[]args){/***try-catch捕获异常**///可能产生的异常try{//catchordeclareread("b.txt");}catch(FileNotFoundExceptione){//使用某种捕获来处理异常System.out.println(e);/***Throwable中的查看方法*getMessage获取异常信息并提示给用户*toString获取异常类型和异常描述(未使用)*printStackTrace**/System.out.println("Throwable常用方法测试");System.out.println(e.getMessage());//文件不存在System.out.println(e.toString());e.printStackTrace();}finally{System.out.println("不管程序是什么,都会在这里执行");}System.out.println("结束");}publicstaticvoidread(Stringpath)throwsFileNotFoundException{if(!path.equals("a.txt")){thrownewFileNotFoundExceptiontion("文件不存在");}}}输出结果为:java.io.FileNotFoundException:Thefiledoesnotexist-----Throwablecommonmethodtest------Thefiledoesnotexistjava.io.FileNotFoundException:Thefile不管怎样程序是,它将在这里执行。注意:trycatchfinally不能单独使用
