最后在Python中添加只是为了更好的可读性

Web*_*ode 0 python exception-handling exception

在此链接(https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions)下面说:

在离开try语句之前总是执行finally子句,无论是否发生了异常.

代码1:

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."
Run Code Online (Sandbox Code Playgroud)

输出1:

Performing an action which may throw an exception.
Everything looks great!
Finally is called directly after executing the try statement whether an exception is thrown or not.
Run Code Online (Sandbox Code Playgroud)

代码2:

try:
    print "Performing an action which may throw an exception."
    raise  Exception('spam', 'eggs') # This is new
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."
Run Code Online (Sandbox Code Playgroud)

输出2:

Performing an action which may throw an exception.
An exception was thrown!
('spam', 'eggs')
Finally is called directly after executing the try statement whether an exception is thrown or not.
Run Code Online (Sandbox Code Playgroud)

我从中得到的else是只有在没有异常时执行.

问:
是否finally只用于更好的可读性?
因为我可以在尝试后把这个print语句放在这个代码中.

代码3:

try:
    print "Performing an action which may throw an exception."
    #raise  Exception('spam', 'eggs') # with this line or without last print is done
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"

print "Finally is called directly after executing the try statement whether an exception is thrown or not."
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

在某些情况下finally套件总是被执行,但您的print声明不会:

  1. 当你的未处理的异常时try.
  2. 当你try处于一个循环(whilefor)中并且你使用了一个breakcontinue语句
  3. 当你try的功能和你使用一个return声明.

finally然后该套件用于保证代码的执行,无论try块中发生了什么,即使在到达块结束之前退出也是如此.

相比:

def foo():
    try:
        print "Performing an action which may throw an exception."
        return
    except Exception as error:
        print "An exception occured!", error
    finally:
        print "Cleaning up"
Run Code Online (Sandbox Code Playgroud)

def bar():
    try:
        print "Performing an action which may throw an exception."
        return
    except Exception as error:
        print "An exception occured!", error
    print "Cleaning up"
Run Code Online (Sandbox Code Playgroud)

bar()最后一条消息中没有打印:

>>> foo()
Performing an action which may throw an exception.
Cleaning up
>>> bar()
Performing an action which may throw an exception.
Run Code Online (Sandbox Code Playgroud)