s-day05-try...catch异常处理方式以及执行流程
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package com.inmind.exception_trycatch02;
|
||||
|
||||
|
||||
/*
|
||||
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 Demo06 {
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.out.println("try中的方法----开始了【1】");
|
||||
int[] arr = {1, 2, 3, 4, 5};
|
||||
int resutl = getValue(arr,8);
|
||||
System.out.println("try中的方法----结束了【2】");
|
||||
// }catch (NullPointerException e){//捕获空指针异常,如果捕获错了,异常还是存在的,会交给JVM处理
|
||||
}catch (ArrayIndexOutOfBoundsException e){
|
||||
System.out.println("捕获了异常----【3】");
|
||||
System.out.println("处理了数组索引越界异常");
|
||||
}
|
||||
System.out.println("程序结束-----【4】");
|
||||
}
|
||||
private static int getValue(int[] arr, int i) {
|
||||
if (i >= arr.length - 1 || i < 0) {
|
||||
String msg = "数组的最大索引为"+(arr.length-1)+",当前索引"+i+"不合法";
|
||||
throw new ArrayIndexOutOfBoundsException(msg);//抛出的是运行时异常,编译时期不提示处理的
|
||||
}
|
||||
return arr[i];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user