除了Python之外,什么时候需要向try.添加`else`子句?
当我用Python编写带有异常处理的代码时,我可以编写如下代码:除了Python之外,什么时候需要向try.添加`else`子句?,python,exception,Python,Exception,当我用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() excep
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\u需要在没有异常时运行()
将在没有异常时执行。有什么区别吗?实际上,在第二个代码段中,最后一行始终执行
你可能是说
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
版本,如果它能让代码更具可读性的话。在第二个示例中,如果您不想在没有异常时捕获需要运行的code\u中的异常,请使用else
变量。在第二个示例中,code\u在没有异常时需要运行的
将在发生异常时运行,然后您处理它,在事件结束后继续
所以
在这两种情况下,当没有异常时,将执行\u需要\u运行\u的代码\u,但在后一种情况下,将在有异常和无异常时执行
在您的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()
它将输出
例1
处理异常
例2
处理异常
做得更多
例3
做得更多
例4
做得更多
你明白了,玩转除了例外,泡泡和其他东西!破解命令行和VIM 根据
“当控制从try子句末尾流出时,将执行可选else子句。7.2 else子句中的异常不由前面的except子句处理。”
因此,请看这个基本示例作为您的答案
try:
print("Try with Exception")
print(sys.path)
except NameError:
print "Exception"
else:
print "Else"
print("Out of try/except block")
try:
print("Try without Exception")
except NameError:
print "Exception"
else:
print "Else is now executed"
print("Out of try/except finally")
查看异常未发生时else是如何执行的 示例1:
try:
a()
b()
except:
c()
在这里,b()
只在a()
没有抛出的情况下运行,但是except块还将捕获b()
可能抛出的任何异常,这可能是您不想要的。一般规则是:只捕获您知道可能发生的异常(并且有一种处理方法)。因此,如果您不知道b()
是否会抛出,或者如果捕获b()
抛出的异常无法做任何有用的事情,那么不要将b()
放入try:
块
例2:
try:
a()
except:
c()
else:
b()
在这里,b()
只有在a()
没有抛出的情况下才会运行,但是b()
抛出的任何异常都不会在这里被捕获,并将继续向上传播堆栈。这通常是你想要的
例3:
try:
a()
except:
c()
b()
在这里,b()
总是运行,即使a()
没有抛出任何东西。当然,这也非常有用。您的原始代码几乎正确。以下是完整的治疗:
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()
code_that_runs_whether_there_was_an_exception_or_not()
我已经很久没有使用Python了,但是我尝试在try
块中处理特定的异常,并使用else
来处理我可能没有预料到的“其他”异常,类似于C/C++开关中的default
块。这是否也适用于else
呢?我使用try:…除了:…else:很多
这是一种模式:try..except应该只跨一行代码,我预期会出现异常。然后除了执行回退/默认处理外,还有:执行我真正想做的事情(无异常=>继续做我想做的事情)
一个简单的例子:
# Exhibit 1
data_paths = []
try:
from . import version_subst
except ImportError:
first_datadir = "./data"
else:
first_datadir = os.path.join(version_subst.DATADIR, PACKAGE_NAME)
# Exhibit 2
for attr in attrs:
try:
obj = getattr(plugin, attr)
except AttributeError, e:
if warn:
pretty.print_info(__name__, "Plugin %s: %s" % (plugin_name, e))
yield None
else:
yield obj
虽然Ned Batchelder的回答适合OP,但我想在此基础上稍作补充。另外,我不能回复Mk12的评论(因为我“只有”49个代表,而不是50个,如图所示)。因此,我的一点贡献是:
try:
code_that_can_cause_an_exception()
except ParticularException:
code_to_handle_the_particular_exception()
except:
code_to_handle_all_other_exceptions()
else:
code_to_run_when_there_are_no_exceptions_and_which_should_not_be_run_after_except_clauses()
finally:
code_to_run_whether_there_was_an_exception_or_not_even_if_the_program_will_exit_from_the_try_block()
code_to_run_whether_there_was_an_exception_or_not_if_execution_reaches_here()
是的,第二个代码段始终会执行,但第一个代码段与您的示例之间的可读性/风格差异远远不止这些。在第一个代码段中,需要运行的代码永远不会导致某些代码处理异常()运行,而在您的代码段中它可以。David,您是对的。正如你所见,在你发表评论前30秒我意识到:)忽略我上面的帖子根本不起作用。帮我把书还给我!运行的code\u不应该在finally块中吗?