try{} catch{} finally{} 语句注意事项总结

来源:互联网 发布:超级基因优化液txt全集下载 编辑:程序博客网 时间:2024/04/28 02:08
try{} catch{} finally{} 语句注意事项:

  • 如果有一个catch{}语句匹配上,其他catch{}分支就不会执行了
  • try{}里面如果有return,也会先执行finally{}里面的语句,之后再return
  • 如果try{}和finally{}里面都与return语句,则try{}里面的return不会被执行
  • finally{}部分什么情况下不会被执行?
    • 在try{}之前就return的情况
    • 在try{}里面有System.exit()的情况
    • 线程被interrupted/killed的情况
    • 死机、停电
  • 如果在finally{}里面出现异常,有什么后果?
    • 会覆盖try{}里面的异常,导致try{}里面的异常无法被捕捉到
    • 会导致finally{}异常后面的代码不会被执行
    • 会被调用者捕获
  • 如果在finally{}里面会出现异常,怎么解决?
    • 留给调用者去解决
    • 在finally{}里面捕获后,写进日志里面

参考文章:《 The Java Tutorials 》:

The finally Block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return,continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.


0 0
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 猫不吃饭精神不好怎么办 运动完头晕目眩想吐怎么办 酒后第二天恶心想吐怎么办 剧烈运动后肌肉酸痛怎么办 剧烈运动后吐了怎么办 长跑后头晕想吐怎么办 运动后一直想吐怎么办 跑多了恶心想吐怎么办 剧烈运动恶心想吐怎么办 长跑之后 恶心想吐怎么办 喝咖啡后绞心痛怎么办 牛奶喝多了胃胀怎么办 运动后大量出汗头晕怎么办 屁股出汗淹的特别痛怎么办 运动完感觉很累怎么办 跑步后感觉很累怎么办 输液多了伤脾胃怎么办 运动完后特别晕怎么办 运动过量大腿肌肉酸痛怎么办 13岁发烧38.2度怎么办 头晕恶心想吐四肢无力怎么办 烧退了浑身疼怎么办 下午睡久了头疼怎么办 一天睡久了头疼怎么办 在家躺久了头疼怎么办 4周多儿童睡眠差怎么办 6岁儿童睡眠差怎么办 四年级的孩子不会写作文怎么办 四年级的孩子写不出作文怎么办? 欠了三万网贷怎么办 打完篮球浑身疼怎么办 在部队当兵意外死亡了怎么办 派派没有体力瓶怎么办 e记账登录不上怎么办 洁净净化区湿度高怎么办 政府测量土地少算了面积怎么办 北京武警欠我钱怎么办 被小混混打了怎么办 农保地建房子怎么办 WOW7.3到8.0橙装怎么办 90后离婚有孩子怎么办