++计算
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
中的内容还是会执行,并且是先执行finally
再return
。
2、需要注意的是,如果返回的是一个基本数据类型,则finally
中的内容对返回的值没有影响。因为返回的是 finally
执行之前生成的一个副本。
3、当catch
和finally
都有return
时,return
的是finally
的值。
标签:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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可重复读、避免幻读原理