进阶day04-try..catch...finally的格式以及执行流程
This commit is contained in:
45
javaSE-day05/src/com/inmind/try_catch04/FinallyDemo07.java
Normal file
45
javaSE-day05/src/com/inmind/try_catch04/FinallyDemo07.java
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package com.inmind.try_catch04;
|
||||||
|
/*
|
||||||
|
try..catch...finally的格式以及执行流程
|
||||||
|
1.try..catch...finally的作用:保证一段代码不管是否出现异常,不管该异常是否被处理,此段代码都一定执行.(IO流的资源释放,数据库连接资源释放)
|
||||||
|
2.try..catch...finally的语法:
|
||||||
|
try{
|
||||||
|
可能会出现异常的代码
|
||||||
|
}catch(异常名 变量名){
|
||||||
|
捕获了异常之后,异常处理代码
|
||||||
|
}finally{
|
||||||
|
一定要执行的代码
|
||||||
|
}
|
||||||
|
|
||||||
|
3.try..catch...finally的执行流程:
|
||||||
|
a.当try中的代码,如果没有发生异常,那么try中的代码正常执行结果,并且catch就不会执行
|
||||||
|
,try-catch之后一定会执行finally中的代码.
|
||||||
|
b.当try中的代码,如果发生异常,那么try中在发生异常之后的代码就不会执行了,
|
||||||
|
如果catch捕获到异常,catch后面的代码会执行,try-catch之后一定会执行finally中的代码,程序正常执行
|
||||||
|
c.当try中的代码,如果发生异常,那么try中在发生异常之后的代码就不会执行了,
|
||||||
|
如果catch没有捕获到异常,catch后面的代码不会执行,try-catch之后一定会执行finally中的代码,异常交给JVM,程序异常终止
|
||||||
|
|
||||||
|
总结:finally的使用场景就是不管有没有异常一定要执行的代码就写在finally中,比如IO流的系统资源释放,数据库连接资源的释放
|
||||||
|
*/
|
||||||
|
public class FinallyDemo07 {
|
||||||
|
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】");
|
||||||
|
} finally {
|
||||||
|
System.out.println("finally----【4】");
|
||||||
|
}
|
||||||
|
System.out.println("程序结束------【5】");
|
||||||
|
}
|
||||||
|
private static int getByIndex(int[] arr, int index) {
|
||||||
|
int result = arr[index];//JVM只会创建越界异常
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user