• 请不要在回答技术问题时复制粘贴 AI 生成的内容
drymonfidelia
V2EX  ›  程序员

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

  •  
  •   drymonfidelia · Mar 19, 2024 · 1961 views
    This topic created in 804 days ago, the information mentioned may be changed or developed.
    4 replies    2024-03-19 20:07:37 +08:00
    ysc3839
        1
    ysc3839  
       Mar 19, 2024 via Android
    return 也会执行
    google2020
        2
    google2020  
       Mar 19, 2024   ❤️ 1
    try 或 catch 可以 return ,return 之后外面的就不跑了,但 final 会照样跑
    mxT52CRuqR6o5
        3
    mxT52CRuqR6o5  
       Mar 19, 2024
    其他语言不清楚,js 的 final 块可以改变 try/catch 中已经 return 的返回值
    geelaw
        4
    geelaw  
       Mar 19, 2024   ❤️ 1
    楼上已经说过 return 的时候 finally 会执行,把必须执行的代码写在 finally 里面而不是后面对阅读更好。另外就是

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

    里面 other 是会执行的,another 不会执行。当然你可以说 another 可以挪到最外面的 catch 后面,但是这样会导致整个程序不能非平凡地使用方法,因为最外面的 catch ,在一段“正常书写”的代码里,不一定在当前方法里面。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3537 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 10:48 · PVG 18:48 · LAX 03:48 · JFK 06:48
    ♥ Do have faith in what you're doing.