您的位置:首页 > 其它

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

2017-09-14 16:04 483 查看
(转载)http://blog.csdn.net/clementad/article/details/46537477

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.

还可以参考:

http://www.cnblogs.com/lanxuezaipiao/p/3440471.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: