Java学习笔记__异常机制_try_catch_finally_return执行顺序

时间:2023-03-09 09:18:39
Java学习笔记__异常机制_try_catch_finally_return执行顺序
 package cn.xiaocangtian.Exception;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; public class TestException3 {
public static void main(String[] args) {
String str = new TestException3().openFile();
System.out.println(str); } String openFile() {
/**
* 执行顺序 1. 执行 try {} catch () {}
* 2. 执行 finally 如果在finally中有return语句,则不会再指行try or catch 中的return了!
* 3. 最后执行try or catch 中 的return 语句
*/
try {
System.out.println("aaa");
FileInputStream fls = new FileInputStream("E:/Java_All_Code/Test/test1.txt"); //对应FileNotFoundException
int a = fls.read(); //对应 IOException
System.out.println("bbb");
return "Step0"; //文件打开成功,则是应该在这里执行return
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Catching1.。..");
e.printStackTrace();
return "Step1"; //如果文件打开失败,则应该在这里执行return
} catch (IOException e) {
System.out.println("Catching2....");
e.printStackTrace();
return "Step2";
} finally {
System.out.println("Finally !!!");
// return "fff"; //不要在finally中使用 return!!虽然可以用,但是习惯不好,会覆盖try or catch中的return
} }
}