进阶day04-try...catch异常处理方式以及执行流程
This commit is contained in:
42
javaSE-day05/src/com/inmind/try_catch04/TryCatchDemo06.java
Normal file
42
javaSE-day05/src/com/inmind/try_catch04/TryCatchDemo06.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.inmind.try_catch04;
|
||||
/*
|
||||
try...catch异常处理方式以及执行流程
|
||||
|
||||
之前throws关键字只是将异常声明出去,没有真正地处理,那么如何真的解决掉异常呢???
|
||||
|
||||
1.try...catch的作用:真的处理掉了异常,JVM就不会再得到异常,程序会正常执行
|
||||
2.try...catch语法:
|
||||
try{
|
||||
可能会出现异常的代码
|
||||
}catch(指定异常类名 变量名){
|
||||
捕获了异常之后,异常处理代码
|
||||
}
|
||||
|
||||
3.try...catch执行流程:
|
||||
a.当try中的代码,如果没有发生异常,那么try中的代码正常执行结果,并且catch就不会执行.
|
||||
b.当try中的代码,如果发生异常,那么try中在发生异常之后的代码就不会执行了,
|
||||
如果catch捕获到异常,catch后面的代码会执行,程序正常执行
|
||||
c.当try中的代码,如果发生异常,那么try中在发生异常之后的代码就不会执行了,
|
||||
如果catch没有捕获到异常,catch后面的代码不会执行,异常交给JVM,程序异常终止
|
||||
*/
|
||||
public class TryCatchDemo06 {
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.out.println("try---------start【1】");
|
||||
int[] arr = {1, 2, 3, 4, 5};
|
||||
int result = getByIndex(arr, 6);
|
||||
System.out.println(result);
|
||||
System.out.println("try---------end【2】");
|
||||
} catch (NullPointerException e) {
|
||||
System.out.println(e);
|
||||
System.out.println("处理了索引越界异常");
|
||||
System.out.println("catch---------【3】");
|
||||
}
|
||||
System.out.println("程序结束------【4】");
|
||||
}
|
||||
|
||||
private static int getByIndex(int[] arr, int index) {
|
||||
int result = arr[index];//JVM只会创建越界异常
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user