"The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement."
https://docs.python.org/3/tutorial/errors.html
看了半天没琢磨明白用 else 相比直接写到 try 里有什么好处
补充:"wasn’t raised by the code ..." 具体指什么情况? 举个例子?
如果用 try ... except 很可能会捕获到自己不想要的类型的异常,或自己不期望的函数抛出的异常。
比如这样的代码:
OSError 可能有自己不期待的异常类型,或者不是文件操作引起的异常。
如果在 except 中处理不当,就会导致对应的异常没有得到正确处理,引起 bug。