zoukankan      html  css  js  c++  java
  • Java趣味分享:try & finally

    考虑以下四个测试方法,它们会输出什么?

    public class Test {
    
        public static void main(String[] args) {
    
            System.out.println(test1());
    
            System.out.println(test2());
    
            System.out.println(test3());
    
            System.out.println(test4());
    
        }
    
        private static int test1() {
    
            int i = 1;
            try {
                return i;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                i = 0;
            }
    
            return i;
    
        }
    
        private static int test2() {
    
            int i = 1;
            try {
                return i;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                i = 0;
                return i;
            }
    
        }
    
        private static User test3() {
    
            User user = new User("u1");
            try {
                return user;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                user = new User("u2");
            }
    
            return null;
    
        }
    
        private static User test4() {
    
            User user = new User("u1");
            try {
                return user;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                user.setName("u2");
            }
    
            return null;
    
        }
    
    }
    
    public class User {
    
        public User(String name) {
            this.name = name;
        }
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return name;
        }
    
    }
    

    答案如下:

    1

    0

    u1

    u2

    结论

    1、不管try,finally都会执行;

    2、在try中return,在finally执行前会把结果保存起来,即使在finally中有修改也以try中保存的值为准,但如果是引用类型,修改的属性会以finally修改后的为准;

    3、如果try/finally都有return,直接返回finally中的return。

    推荐去我的博客阅读更多:

    1.Java JVM、集合、多线程、新特性系列教程

    2.Spring MVC、Spring Boot、Spring Cloud 系列教程

    3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程

    4.Java、后端、架构、阿里巴巴等大厂最新面试题

    觉得不错,别忘了点赞+转发哦!

  • 相关阅读:
    Mysql 命令行连接
    linux下安装MongoDB数据库
    SVN 提交常见报错及解决方案
    解决 SVN Skipped 'xxx' -- Node remains in conflict
    linux svn 切换用户
    SQL基础语法
    yml
    搭建笔记(1)
    文件上传MultipartFile
    18.线程池
  • 原文地址:https://www.cnblogs.com/javastack/p/12849991.html
Copyright © 2011-2022 走看看