当我使用异常处理在Python中编写代码时,我可以编写如下代码:
try:
some_code_that_can_cause_an_exception()
except:
some_code_to_handle_exceptions()
else:
code_that_needs_to_run_when_there_are_no_exceptions()
Run Code Online (Sandbox Code Playgroud)
这有什么不同于:
try:
some_code_that_can_cause_an_exception()
except:
some_code_to_handle_exceptions()
code_that_needs_to_run_when_there_are_no_exceptions()
Run Code Online (Sandbox Code Playgroud)
在这两种情况下code_that_needs_to_run_when_there_are_no_exceptions()都会在没有例外时执行.有什么不同?
在第二个例子,code_that_needs_to_run_when_there_are_no_exceptions()当你将跑做有一个例外,那你处理它,除了在前后继续.
所以......
在这两种情况下,code_that_needs_to_run_when_there_are_no_exceptions()将在没有异常时执行,但后者将在有异常时执行.
在CLI上试试这个
#!/usr/bin/python
def throws_ex( raise_it=True ):
if raise_it:
raise Exception("Handle me")
def do_more():
print "doing more\n"
if __name__ == "__main__":
print "Example 1\n"
try:
throws_ex()
except Exception, e:
# Handle it
print "Handling Exception\n"
else:
print "No Exceptions\n"
do_more()
print "example 2\n"
try:
throws_ex()
except Exception, e:
print "Handling Exception\n"
do_more()
print "example 3\n"
try:
throws_ex(False)
except Exception, e:
print "Handling Exception\n"
else:
do_more()
print "example 4\n"
try:
throws_ex(False)
except Exception, e:
print "Handling Exception\n"
do_more()
Run Code Online (Sandbox Code Playgroud)
它会输出
例1
处理异常
例2
处理异常
做得更多
例3
做得更多
例4
做得更多
你明白这个想法,玩弄异常,冒泡和其他东西!破解命令行和VIM!
实际上,在第二个片段中,最后一行始终执行.
你可能意味着
try:
some_code_that_can_cause_an_exception()
code_that_needs_to_run_when_there_are_no_exceptions()
except:
some_code_to_handle_exceptions()
Run Code Online (Sandbox Code Playgroud)
我相信你可以使用该else版本,如果它使代码更具可读性.else如果您不想捕获异常,请使用该变体code_that_needs_to_run_when_there_are_no_exceptions.
例1:
try:
a()
b()
except:
c()
Run Code Online (Sandbox Code Playgroud)
这里b()只会在a()没有抛出的情况下运行,但except块也会捕获可能抛出的b()任何异常,这可能是您不想要的.一般规则是:只捕获您知道可能发生的异常(并且有一种处理方式).因此,如果你不知道是否b()会抛出,或者如果您不能通过捕捉被抛出的异常做任何有用的事情b(),那么不要把b()在try:块.
例2:
try:
a()
except:
c()
else:
b()
Run Code Online (Sandbox Code Playgroud)
这里b()只会在a()没有抛出的情况下运行,但抛出的任何异常b()都不会在这里被捕获并继续向上传播.这通常是你想要的.
例3:
try:
a()
except:
c()
b()
Run Code Online (Sandbox Code Playgroud)
在这里,b()总是运行,即使a()没有抛出任何东西.当然,这也是非常有用的.