try-catch-finally-return的执行顺序和try-with-resource语法糖

try-catch-finally-return的执行顺序

总结如下几条情况

  1. ·try-catch-finally都有return语句时,没有异常时,返回值是finally中的return返回的·。

    • 执行try块,执行到return语句时,先执行return的语句
    • 但是不返回到main方法,执行finally块,遇到finally块中的return语句
    • 并将值返回到main方法,这里就不会再回去返回try块中计算得到的值
    • 所以最终的值是finally的返回
    • 举例如下
      public static void main(String[] args) throws ParseException {
          int i = NoException();
          System.out.println("最终值: " + i);
      }
      
      public static int NoException() {
          int i = 10;
          try {
              System.out.println("i in try block is:" + i);
              return --i;
          } catch (Exception e) {
              --i;
              System.out.println("i in catch - form try block is:" + i);
              return --i;
          } finally {
              System.out.println("i in finally - from try or catch block is:" + i);
              return --i;
          }
      }
      /*
      i in try block is:10
      i in finally - from try or catch block is:9
      最终值: 8
      
      */
      
  2. try-catch都有return语句时,没有异常时,返回值是try中的return返回的

    • try中执行完return的语句后,不返回,执行finally块
    • finally块执行结束后,返回到try块中
    • 最后,返回在try块中最后的值
    • 举例如下
      public static void main(String[] args) throws ParseException {
         int i = NoException();
         System.out.println("最终值: " + i);
      }
      
      public static int NoException() {
         int i=10;
         try{
             System.out.println("i in try block is:"+i);
             return --i;
         }
         catch(Exception e){
             --i;
             System.out.println("i in catch - form try block is:"+i);
             return --i;
         }
         finally{
             System.out.println("i in finally - from try or catch block is:"+i);
             --i;
             System.out.println("i in finally block is:"+i);
             //return --i;
         }
      }
      /*
      i in try block is:10
      i in finally - from try or catch block is:9
      i in finally block is:8
      最终值: 9
      */
      
  3. try块中抛出异常,try、catch和finally中都有return语句,返回值是finally中的return。

    • 抛出异常后,执行catch块,在catch块的return的执行完后
    • 并不直接返回而是执行finally,因finally中有return语句,所以,执行finally里面的语句
    • 最终返回finally的return
    • 举例如下
      public static void main(String[] args) throws ParseException {
          int i = NoException();
          System.out.println("最终值: " + i);
      }
      
      public static int NoException() {
          int i = 10;
          try {
              System.out.println("i in try block is:" + i);
              i = i / 0;
              return --i;
          } catch (Exception e) {
              System.out.println("i in catch - form try block is:" + i);
              --i;
              System.out.println("i in catch block is:" + i);
              return --i;
          } finally {
              System.out.println("i in finally - from try or catch block is--" + i);
              --i;
              System.out.println("i in finally block is--" + i);
              return --i;
          }
      }
      /*
      i in try block is:10
      i in catch - form try block is:10
      i in catch block is:9
      i in finally - from try or catch block is--8
      i in finally block is--7
      最终值: 6
      
      */
      
  4. try块中抛出异常,try和catch中都有return语句,返回的catch中return值。

    • 抛出异常后,执行catch块
    • 执行完finally语句后,依旧返回catch中的执行return语句后的值,而不是finally中修改的值。
    • 举例如下
      public static void main(String[] args) throws ParseException {
          int i = NoException();
          System.out.println("最终值: " + i);
      }
      
      public static int NoException() {
          int i = 10;
          try {
              System.out.println("i in try block is:" + i);
              i = i / 0;
              return --i;
          } catch (Exception e) {
              System.out.println("i in catch - form try block is:" + i);
              return --i;
          } finally {
      
              System.out.println("i in finally - from try or catch block is:" + i);
              --i;
              System.out.println("i in finally block is:" + i);
              //return i;
          }
      }
      /*
      i in try block is:10
      i in catch - form try block is:10
      i in finally - from try or catch block is:9
      i in finally block is:8
      最终值: 9
      */
      
  5. try、catch中都出现异常,在finally中有返回,返回finally中return值

    • try块中出现异常到catch,catch中出现异常到finally
    • finally中执行到return语句返回,不检查异常。
    • 举例如下
      public static void main(String[] args) throws ParseException {
          int i = NoException();
          System.out.println("最终值: " + i);
      }
      
      public static int NoException() {
          int i = 10;
          try {
              System.out.println("i in try block is:" + i);
              i = i / 0;
              return --i;
          } catch (Exception e) {
              System.out.println("i in catch - form try block is:" + i);
              int j = i / 0;
              return --i;
          } finally {
              System.out.println("i in finally - from try or catch block is:" + i);
              --i;
              System.out.println("i in finally block is:" + i);
              return --i;
          }
      }
      /*
      i in try block is:10
      i in catch - form try block is:10
      i in finally - from try or catch block is:10
      i in finally block is:9
      最终值: 8
      */
      

try-with-resource语法糖

JDK7之后,Java多了个新的语法:try-with-resources语句,该语句确保在语句执行完毕后,每个资源都被自动关闭 。

可以理解为是一个声明一个或多个资源的 try语句(用分号隔开),一个资源作为一个对象,并且这个资源必须要在执行完关闭的

其实之前的手动关闭,在这个语法糖里面并没有被取消,而是因为编译器,编译器自动帮我们生成了finally块,并且在里面调用了资源的close方法,所以例子中的close方法会在运行的时候被执行。

原理

传统写法

public void readFile() throws FileNotFoundException {
    FileReader fr = null;
    BufferedReader br = null;
    try{
        fr = new FileReader("d:/test.txt");
        br = new BufferedReader(fr);
        String s = "";
        while((s = br.readLine()) != null){
            System.out.println(s);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用当前语法

public void readFile() throws FileNotFoundException {
   try(
           FileReader fr = new FileReader("d:/test.txt");
           BufferedReader br = new BufferedReader(fr)
   ){
       String s = "";
       while((s = br.readLine()) != null){
           System.out.println(s);
       }
   } catch (IOException e) {
       e.printStackTrace();
   }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/601221.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

unity基础(二)

debug方法 Debug.Log(" 一般日志 ");Debug.LogWarning(" 警告日志 ");Debug.LogError(" 错误日志 ");// Player Informationstring strPlayerName "Peter";int iPlayerHpValue 32500;short shPlayerLevel 10;long lAdvantureExp 1…

爱普生MCU系列语音芯片S1C31D41

随着科技的发展和产品的集成化,语音芯片已经逐渐替代了多种语音设备应用在各场合。语音芯片主要特性是功耗低,抗干扰能力强,外围器件少,控制简单,语音保存时间久(某些语音芯片可以保存内容100年),掉电不丢失…

yolo-world:”目标检测届大模型“

AI应用开发相关目录 本专栏包括AI应用开发相关内容分享,包括不限于AI算法部署实施细节、AI应用后端分析服务相关概念及开发技巧、AI应用后端应用服务相关概念及开发技巧、AI应用前端实现路径及开发技巧 适用于具备一定算法及Python使用基础的人群 AI应用开发流程概…

【Git】Git学习-16:git merge,且解决合并冲突

学习视频链接: 【GeekHour】一小时Git教程_哔哩哔哩_bilibili​编辑https://www.bilibili.com/video/BV1HM411377j/?vd_source95dda35ac10d1ae6785cc7006f365780 1 创建分支dev,并用merge合并master分支,使dev分支合并上master分支中内容为…

[Algorithm][多源BFS][矩阵][飞地的数量][地图中的最高点][地图分析] + 多源BFS原理讲解 详细讲解

目录 0.原理讲解1.矩阵1.题目链接2.算法原理详解3.代码实现 2.飞地的数量1.题目链接2.算法原理详解3.代码实现 3.地图中的最高点1.题目链接2.算法原理详解3.代码实现 4.地图分析1.题目链接2.算法原理详解3.代码实现 0.原理讲解 注意:只要是用**BFS解决的最短路径问题…

韩顺平0基础学Java——第5天

p72——p86 今天同学跟我说别学java,真的吗?唉,先把这视频干完吧。 逻辑运算符练习 x6,y6 x6,y5 x11,y6 x11,y5 z48 错了&a…

【web网页制作】html+css旅游家乡河南开封主题网页制作(4页面)【附源码】

HTMLCSS家乡河南主题网页目录 🍔涉及知识🥤写在前面🍧一、网页主题🌳二、页面效果Page1 首页Page2 开封游玩Page 3 开封美食Page4 留言 🌈 三、网页架构与技术3.1 脑海构思3.2 整体布局3.3 技术说明书 🐋四…

【Git】Git学习-14:VSCode中使用git

学习视频链接:【GeekHour】一小时Git教程_哔哩哔哩_bilibili​编辑https://www.bilibili.com/video/BV1HM411377j/?vd_source95dda35ac10d1ae6785cc7006f365780 在vscode中打开文件 code . 自行修改内容,在源代码管理器中测试下

flutter报错

组件相关 type ‘List’ is not a subtype of type ‘List’ children: CardList.map((item) > Container( 加上 *** < Widget>*** 正常 type ‘(dynamic, dynamic) > Container’ is not a subtype of type ‘(CardType) > Widget’ of ‘f’ children: CardL…

Spring Data JPA自定义Id生成策略、复合主键配置、Auditing使用

前言 在Spring Data JPA系列的第一篇文章 SpringBoot集成JPA及基本使用-CSDN博客 中讲解了实体类的Id生成策略可以通过GeneratedValue注解进行配置&#xff0c;该注解的strategy为GenerationType类型&#xff0c;GenerationType为枚举类&#xff0c;支持四种Id的生成策略&…

详细讲解lua中string.gsub的使用

string.gsub 是 Lua 标准库中的一个函数&#xff0c;用于全局替换字符串中的某些部分。string.gsub 是 Lua 中非常实用的一个函数&#xff0c;它可以用来进行字符串的处理和替换操作。 它的基本语法如下&#xff1a; string.gsub(s, pattern, replacement [, n])s 是要处理的…

鸿蒙开发核心技术都有哪些【都是从零开始】

鸿蒙开发核心技术都有哪些&#xff1f;&#xff1a;【持续1年的时间公关鸿蒙技术】 我们能做哪些呢&#xff1f; 还是从UI业务开始吧 面试题1&#xff1a; 基于STAGE模型项目重构等问题 代理设计模式&#xff0c;业务与架构隔离 中介者模式&#xff0c;和代理设计模式的区别…

项目管理-项目绩效域1/2

项目管理&#xff1a;每天进步一点点~ 活到老&#xff0c;学到老 ヾ(◍∇◍)&#xff89;&#xff9e; 何时学习都不晚&#xff0c;加油 1.项目绩效域--整体框架 项目绩效域 重点&#xff1a; ①八大绩效域的含义。 ②八大绩效域的问题和解决方案。 ③八大绩效域与十大管…

Go标准库——Flag库和Log库

一.Flag Go语言内置的flag包实现了命令行参数的解析&#xff0c;flag包使得开发命令行工具更为简单。 1.1 os.Args 如果你只是简单的的想要获取命令行参数&#xff0c;可以像下面代码示例一样使用os.Args来获取命令行参数。 os.Arg实际是一个存储命令行参数的字符串切片([]stri…

Linux最新提权通杀五大绝招(上)

点击星标&#xff0c;即时接收最新推文 本文选自《内网安全攻防&#xff1a;红队之路》 扫描二维码五折购书 Linux 主机权限提升问题是普遍存在的。在Web 服务器、数据库、防火墙、IOT等基础设施中&#xff0c;大部分都运行着Linux 操作系统&#xff0c;鉴于Linux 设备在大量基…

【负载均衡在线OJ项目日记】项目简介

目录 前言 什么是负载均衡 所用的技术和开发环境 所用技术 开发环境 项目的宏观结构 leetcode 结构 结构 编写思路 前言 从C语言的文章到现在Linux网络部分&#xff0c;我已经涉猎了很多知识&#xff1b;终于在今天我要开始搞项目了&#xff0c;通过项目我也可以开始…

鸿蒙OS NEXT的推出,不仅面向App端

华为官方公布6月份的版本为beta版&#xff0c;依然属于开发者测试版&#xff0c;但可以向普通用户开放了。这点和苹果iOS系统测试形式略微相似&#xff1a;6月份开放首个测试版&#xff0c;随后过渡到公测版&#xff0c;最后再和年度新机一起发布正式版系统。 如果按照这个进度…

DNS域名解析服务的部署及优化方案

实验要求: 1.配置2台服务器要求如下&#xff1a; a&#xff09;服务器1&#xff1a; 主机名&#xff1a;dns-master.timinglee.org ip地址&#xff1a; 172.25.254.100 配置好软件仓库 b&#xff09;服务器2&#xff1a; 主机名&#xff1a;dns-slave.timinglee.org ip地址&am…

fero - yolo - mamba:基于选择性状态空间的面部表情检测与分类

fero - yolo - mamba:基于选择性状态空间的面部表情检测与分类 摘要IntroductionRelated work FER-YOLO-Mamba: Facial Expression Detection and Classification Based on Selective State Space 摘要 面部表情识别&#xff08;FER&#xff09;在理解人类情绪线索方面起着关键…

S型曲线的几种设计(图像对比度调节)

一般来讲&#xff0c;图像调色模块都会提供“曲线”工具&#xff0c;这是一个极其灵活的功能&#xff0c;绝大部分的调色都可以通过该工具实现&#xff0c;但是曲线功能的交互相对而言比较复杂。出于简便性和效率方面的考量&#xff0c;调色模块往往还会提供一些具有很强的功能…
最新文章