s-day05--try...catch异常处理方式以及执行流程
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package com.inmind.exception01;
|
||||
/*
|
||||
7.try...catch异常处理方式以及执行流程
|
||||
之前throws关键字只是将异常声明出去,交给调用者处理,没有真正地处理异常,那么如何真的解决异常呢???
|
||||
|
||||
try...catch的作用:真的处理掉异常,JVM不会再接收到异常,程序就会正常执行
|
||||
try...catch的语法:
|
||||
try{
|
||||
可能会出现异常的代码或者方法
|
||||
}catch(指定异常类名 变量名){
|
||||
捕获异常后,异常处理代码
|
||||
}
|
||||
|
||||
|
||||
try-catch的执行顺序:
|
||||
1.当try中的代码,如果没有发现异常,那么try中的代码正常执行,并且catch中的代码就不执行
|
||||
2.当try中的代码,如果发现了异常,那么try中在产生异常之后的代码就不会执行,如果catch捕获到异常,那么catch后面的代码会执行,程序正常执行
|
||||
3.当try中的代码,如果发现了异常,那么try中在产生异常之后的代码就不会执行,如果catch没有捕获到异常,
|
||||
那么catch后面的代码也不会执行,会将没有捕获到的异常交给JVM,JVM打印异常信息,程序异常终止
|
||||
*/
|
||||
public class TryCatchDemo06 {
|
||||
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("处理了数组索引越界异常");
|
||||
}
|
||||
|
||||
System.out.println("程序结束---【4】");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user