V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
drymonfidelia
V2EX  ›  程序员

try catch 的 final 块有什么用,直接写在外面不是一样?

  •  
  •   drymonfidelia · 40 天前 · 1374 次点击
    这是一个创建于 40 天前的主题,其中的信息可能已经有所发展或是发生改变。
    4 条回复    2024-03-19 20:07:37 +08:00
    ysc3839
        1
    ysc3839  
       40 天前 via Android
    return 也会执行
    google2020
        2
    google2020  
       40 天前   ❤️ 1
    try 或 catch 可以 return ,return 之后外面的就不跑了,但 final 会照样跑
    mxT52CRuqR6o5
        3
    mxT52CRuqR6o5  
       40 天前
    其他语言不清楚,js 的 final 块可以改变 try/catch 中已经 return 的返回值
    geelaw
        4
    geelaw  
       39 天前   ❤️ 1
    楼上已经说过 return 的时候 finally 会执行,把必须执行的代码写在 finally 里面而不是后面对阅读更好。另外就是

    try { throw something; }
    catch { throw; } // 重新 throw
    finally { other; }
    another;

    里面 other 是会执行的,another 不会执行。当然你可以说 another 可以挪到最外面的 catch 后面,但是这样会导致整个程序不能非平凡地使用方法,因为最外面的 catch ,在一段“正常书写”的代码里,不一定在当前方法里面。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3208 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:58 · PVG 19:58 · LAX 04:58 · JFK 07:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.