在Python中何时需要在try..except添加else子句?
当我在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()
这和下面的代码有什么不同呢:
try:
some_code_that_can_cause_an_exception()
except:
some_code_to_handle_exceptions()
code_that_needs_to_run_when_there_are_no_exceptions()
在这两种情况下,code_that_needs_to_run_when_there_are_no_exceptions()
都会在没有异常发生时执行。那么,它们有什么区别呢?
8 个回答
示例 1:
try:
a()
b()
except:
c()
在这个例子中,只有当 a()
没有出错时,b()
才会被执行。不过,如果 b()
发生了错误,异常处理块会捕捉到这些错误,这可能不是你想要的。一般来说,规则是:只捕捉你知道可能会发生的异常(并且你有办法处理它们)。所以,如果你不确定 b()
是否会出错,或者你无法通过捕捉 b()
抛出的异常做些什么有用的事情,那么就不要把 b()
放在 try:
块里。
示例 2:
try:
a()
except:
c()
else:
b()
在这个例子中,只有当 a()
没有出错时,b()
才会被执行,但 b()
抛出的任何异常在这里不会被捕捉到,而是会继续向上抛出。这通常是你想要的效果。
示例 3:
try:
a()
except:
c()
b()
在这个例子中,b()
总是会被执行,即使 a()
没有出错。这种情况也是相当常见且有用的。
在第二个例子中,code_that_needs_to_run_when_there_are_no_exceptions()
会在你遇到异常并处理完后继续执行,也就是在 except 之后继续。
所以……
在这两种情况下,当没有异常时,code_that_needs_to_run_when_there_are_no_exceptions()
都会执行,但在后者的情况下,无论有没有异常,它都会执行。
在你的命令行试试这个
#!/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()
它会输出
示例 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()
我觉得如果用 你可以使用else
的写法能让代码更容易理解,那就可以用。else
的写法,如果你不想捕捉来自code_that_needs_to_run_when_there_are_no_exceptions
的异常。