随笔 - 545  文章 - 0  评论 - 31  阅读 - 72万 

 


try、catch面试题

++计算

int a = 2;
int b = (a++) << (++a) + (++a);
System.out.println(b + " " + a);

类似a++,++a这样的表达式,值不会边,但是a会变。即:b = 2 << (4 + 5) = 1024

a = 5

try catch中的return finally

先执行catch,再finally

复制代码
public static int xxx(int i) {
        try {
            throw new Exception("异常");
        } catch (Exception e) {
            System.out.println("return.....");
            return i;
        } finally {
            System.out.println("finally.....");
        }
    }

    public static void main(String[] args) {
        System.out.println("数值i:" + xxx(0));
    }

return.....
finally.....
数值i:0

复制代码

最后返回finally中的return

复制代码
public static int xxx(int i) {
        try {
            throw new Exception("异常");
        } catch (Exception e) {
            System.out.println("return.....");
            return 2;
        } finally {
            System.out.println("finally.....");
            return 3;
        }
    }

    public static void main(String[] args) {
        System.out.println("数值i:" + xxx(0));
    }
return.....
finally.....
数值i:3

复制代码

catch中return变量,finally变量计算

复制代码
public static int xxx(int i) {
        try {
            throw new Exception("异常");
        } catch (Exception e) {
            System.out.println("return.....");
            return i;
        } finally {
            ++i;
            System.out.println("finally.....");
        }
    }

    public static void main(String[] args) {
        System.out.println("数值i:" + xxx(0));
    }

return.....
finally.....
数值i:0

 
复制代码

因为这里是值传递,在执行return前,保留了一个i的副本,值为0。

然后再去执行finally,finally完后,到return的时候,返回的并不是当前的i,而是保留的那个副本,也就是0.所以返回结果是0。

catch、finally都return

复制代码
public static int xxx(int i) {
        try {
            throw new Exception("异常");
        } catch (Exception e) {
            System.out.println("return.....");
            return i;
        } finally {
            System.out.println("finally.....");
            ++i;
            return i;
        }
    }

    public static void main(String[] args) {
        System.out.println("数值i:" + xxx(0));
    }

return.....
finally.....
数值i:1

复制代码

如果finally中有return,不会走catch中的return。

小结

1、在catch中有return的情况下,finally中的内容还是会执行,并且是先执行finallyreturn

2、需要注意的是,如果返回的是一个基本数据类型,则finally中的内容对返回的值没有影响。因为返回的是 finally执行之前生成的一个副本。

3、当catchfinally都有return时,return的是finally的值。

 

posted on   反光的小鱼儿  阅读(234)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2019-04-23 Mysql可重复读、避免幻读原理
点击右上角即可分享
微信分享提示