zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    大数据之 Spark
    设计模式之——外观or门面模式
    架构设计
    Spring
    高并发系列之——负载均衡,web负载均衡
    高并发系列之——原子性和可见性
    高并发系列之——缓存中间件Redis
    mybatis
    JVM读书笔记
    mybatis中一对一关系映射
  • 原文地址:https://www.cnblogs.com/douzujun/p/6142242.html
Copyright © 2011-2022 走看看