【问题标题】:when i run a try except statement to catch a IndentationError ,the statement doesn't work [duplicate]当我运行 try except 语句来捕获 IndentationError 时,该语句不起作用[重复]
【发布时间】:2017-09-22 07:39:14
【问题描述】:

当我运行 try except 语句来捕获 IndentationError 时,该语句不起作用,这是我的代码:

try: 
    for i in range(2):
    print(i)
except IndentationError:
    print('IndentationError')

然后我得到了结果:

try: 
    for i in range(2):
    print(i)
except IndentationError:
    print('IndentationError')
File "<ipython-input-57-5df0f4cccb57>", line 3
print(i)
    ^
IndentationError: expected an indented block```

为什么 try except 语句在这种情况下不起作用?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    IndentationError 和其他SyntaxError 异常无法在源文件本身中捕获,因为这是解析阶段异常。 try此时没有运行,因为在这个阶段代码不能被解析和编译成字节码。

    您只能在触发解析的代码中捕获此类异常,例如import 语句或显式compile() 函数调用。

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 2020-06-08
      • 2011-09-29
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2019-12-31
      • 2020-06-23
      • 2013-04-10
      相关资源
      最近更新 更多