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

 1 package cn.xiaocangtian.Exception;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 
 7 public class TestException3 {
 8     public static void main(String[] args) {
 9         String str = new TestException3().openFile();
10         System.out.println(str);
11         
12     }
13     
14     String openFile() {
15         /**
16          * 执行顺序 1. 执行 try {} catch () {} 
17          *       2. 执行 finally 如果在finally中有return语句,则不会再指行try or catch 中的return了!
18          *       3. 最后执行try or catch 中 的return 语句
19          */
20         try {
21             System.out.println("aaa");
22             FileInputStream fls = new FileInputStream("E:/Java_All_Code/Test/test1.txt");  //对应FileNotFoundException
23             int a = fls.read();               //对应 IOException
24             System.out.println("bbb");
25             return "Step0";                   //文件打开成功,则是应该在这里执行return
26         } catch (FileNotFoundException e) {
27             // TODO Auto-generated catch block
28             System.out.println("Catching1.。..");
29             e.printStackTrace();
30             return "Step1";                   //如果文件打开失败,则应该在这里执行return
31         } catch (IOException e) {
32             System.out.println("Catching2....");
33             e.printStackTrace();
34             return "Step2";
35         } finally {
36             System.out.println("Finally !!!");
37 //            return "fff";           //不要在finally中使用  return!!虽然可以用,但是习惯不好,会覆盖try or catch中的return
38         }
39         
40     }
41 }
原文地址:https://www.cnblogs.com/douzujun/p/6142242.html