{"action":"closed","issue":{"url":"https://api.github.com/repos/trdcaz/trdcaz/issues/12","labels_url":"https://api.github.com/repos/trdcaz/trdcaz/issues/12/labels{/name}","comments_url":"https://api.github.com/repos/trdcaz/trdcaz/issues/12/comments","events_url":"https://api.github.com/repos/trdcaz/trdcaz/issues/12/events","html_url":"https://github.com/trdcaz/trdcaz/issues/12","id":122057897,"number":12,"title":"Python错误处理机制中的else与finally","user":{"login":"trdcaz","id":8707958,"avatar_url":"https://avatars.githubusercontent.com/u/8707958?v=3","gravatar_id":"","url":"https://api.github.com/users/trdcaz","html_url":"https://github.com/trdcaz","followers_url":"https://api.github.com/users/trdcaz/followers","following_url":"https://api.github.com/users/trdcaz/following{/other_user}","gists_url":"https://api.github.com/users/trdcaz/gists{/gist_id}","starred_url":"https://api.github.com/users/trdcaz/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/trdcaz/subscriptions","organizations_url":"https://api.github.com/users/trdcaz/orgs","repos_url":"https://api.github.com/users/trdcaz/repos","events_url":"https://api.github.com/users/trdcaz/events{/privacy}","received_events_url":"https://api.github.com/users/trdcaz/received_events","type":"User","site_admin":false},"labels":[],"state":"closed","locked":false,"assignee":null,"milestone":null,"comments":1,"created_at":"2015-12-14T14:52:50Z","updated_at":"2015-12-14T14:54:32Z","closed_at":"2015-12-14T14:54:32Z","body":"最近看到一个关于Python的`try .. finally ..`问题：如果在`try`子句中`return`了，返回的是什么呢？\r\n\r\n实践是检验真理的唯一标准，搞一下不就知道了：\r\n```python\r\n>>> def test():\r\n...     try:\r\n...         print(\"try:\")\r\n...         return 1\r\n...     finally:\r\n...         print(\"finally:\")\r\n...         return 2\r\n...\r\n>>> test()\r\ntry:\r\nfinally:\r\n2\r\n>>>\r\n```\r\n\r\n再引用下[Python官方文档](https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions)的说明：\r\n> A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.\r\n\r\n简单点说，`finally ..`一定会被执行。\r\n\r\n- - -\r\n\r\n`try .. except ..`还有一个可选的`else ..`子句，当`try ..`没有触发`Exception`的时候，它就会被执行。\r\n`else ..`在某些情况下很有用，可以减少代码量，并且更优雅。\r\n\r\nBTW：在`for ..`和`while ..`中也是可以使用`else ..`的，当循环没有触发`break`的时候，它就会被执行。"}}