我已经阅读了"加注"的官方定义,但我仍然不太明白它的作用.
简单来说,什么是"提高"?
示例用法会有所帮助.
在Python中,if语句中的变量范围是否在if语句之外可见?(来自Java背景,所以发现这有点奇怪)
在下面的例子中,name首先在if-block中定义,但变量在if-block之外也是可见的.我原以为会发生错误但是'joe'会打印出来.
if 1==1:
name = 'joe'
print(name)
Run Code Online (Sandbox Code Playgroud) 以下是我在Doug Hellman网站上发现的一个名为"masking_exceptions_catch.py"的文件中的示例.我暂时无法找到该链接.抛出throws()中引发的异常,同时报告由cleanup()引发的异常.
在他的文章中,Doug评论说处理是非直观的.中途期望它是Python版本中的一个bug或限制(大约在2009年),我在Mac的当前生产版本中运行它(2.7.6).它仍然报告cleanup()的异常.我发现这有点惊人,并希望看到它是如何实际正确或理想的行为的描述.
#!/usr/bin/env python
import sys
import traceback
def throws():
raise RuntimeError('error from throws')
def nested():
try:
throws()
except:
try:
cleanup()
except:
pass # ignore errors in cleanup
raise # we want to re-raise the original error
def cleanup():
raise RuntimeError('error from cleanup')
def main():
try:
nested()
return 0
except Exception, err:
traceback.print_exc()
return 1
if __name__ == '__main__':
sys.exit(main())
Run Code Online (Sandbox Code Playgroud)
节目输出:
$ python masking_exceptions_catch.py
Traceback (most recent call last):
File "masking_exceptions_catch.py", line 24, in main
nested()
File "masking_exceptions_catch.py", line …Run Code Online (Sandbox Code Playgroud)