码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-17 21:38:28      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:java   异常   try   catch   finally   

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.


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

标签:java   异常   try   catch   finally   

原文地址:http://blog.csdn.net/clementad/article/details/46537477

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!