diff --git a/s-day05/src/com/inmind/exception01/TryCatchFinallyDemo07.java b/s-day05/src/com/inmind/exception01/TryCatchFinallyDemo07.java new file mode 100644 index 0000000..f5f5515 --- /dev/null +++ b/s-day05/src/com/inmind/exception01/TryCatchFinallyDemo07.java @@ -0,0 +1,53 @@ +package com.inmind.exception01; +/* +8.try..catch...finally的格式以及执行流程 + +try...catch....finally的作用:保证一段代码不管是否出现异常,不管该异常是否被处理,此段代码一定执行(IO的资源释放,数据库连接资源释放) +try...catch....finally的语法: + try{ + 可能会出现异常的代码或者方法 + }catch(指定异常类名 变量名){ + 捕获异常后,异常处理代码 + }finally{ + 一定要执行的代码 + } + + +try-catch....finally的执行顺序: + 1.当try中的代码,如果没有发现异常,那么try中的代码正常执行,并且catch中的代码就不执行, + 遇到finally中的代码正常执行 + 2.当try中的代码,如果发现了异常,那么try中在产生异常之后的代码就不会执行,如果catch捕获到异常,那么catch后面的代码会执行, + 遇到finally中的代码正常执行,程序正常执行 + 3.当try中的代码,如果发现了异常,那么try中在产生异常之后的代码就不会执行,如果catch没有捕获到异常, + 那么catch后面的代码也不会执行, + 遇到finally中的代码正常执行,执行完Finally之后,会将没有捕获到的异常交给JVM,JVM打印异常信息,程序异常终止 + */ +public class TryCatchFinallyDemo07 { + public static void main(String[] args) { + + try { + System.out.println("try的代码-------开始了【1】"); + int[] arr = {1, 2, 3, 4, 5}; + int result = getValue(arr, 8); + System.out.println("try的代码-------结束了【2】"); + }catch (NullPointerException e){ +// }catch (ArrayIndexOutOfBoundsException e){ + System.out.println("捕获了异常---【3】"); + System.out.println("处理了数组索引越界异常"); + }finally { + System.out.println("finally中的代码执行了-----【4】"); + } + + System.out.println("程序结束---【5】"); + } + + private static int getValue(int[] arr, int index) { + //先判断索引是否规范,不规范则主动自己抛出一个越界异常 + if (index < 0 || index >= arr.length) { + String msg = "数组的最大索引为:"+(arr.length-1)+",当前索引"+index+",是不合法的"; + throw new ArrayIndexOutOfBoundsException(msg);//程序自己抛出异常而不是jvm + } + int result = arr[index];//ArrayIndexOutOfBoundsException + return result; + } +}