【问题标题】:Try to Handle IndentationError Exception尝试处理 IndentationError 异常
【发布时间】:2019-07-11 20:21:14
【问题描述】:

当我尝试处理以下代码中的IndentatioError时..

try:
   def Test():
   print("Test Function")
except IndentationError:
   print("Exception raised")

我在输出中收到此错误:

File "C:/Users/PycharmProjects/py1/Exception.py", line 3
    print("Test Function")
        ^
IndentationError: expected an indented block

Process finished with exit code 1

我接受输出中的 except 部分。

我想知道如何处理这种类型的异常。

【问题讨论】:

标签: python python-3.x exception


【解决方案1】:

你不能。

IndentationError 在“编译”时间引发。 try-except 只能处理运行时引发的异常。

还有什么意义? IndentationError 源自格式错误的代码。不是你可以重新格式化except 块中的代码,重新编译它并重新执行它(理论上你可以,它只是非常复杂)。

【讨论】:

    【解决方案2】:

    在执行程序之前,编译器会检查你的代码是否有正确的缩进,如果没有,就会引发IndentationError。所以一般来说,你会得到IndentationError之前你在代码验证阶段得到except部分代码,而不是执行部分。 所以修复它的方法是简单地进行适当的缩进如下:

    try:
       def Test():
           print("Test Function") //here's the missing tab, that compiler points to
    except IndentationError:
       print("Exception raised")
    

    总结以上内容 - 如果IndentationError try-except 构造无用。

    【讨论】:

      【解决方案3】:

      你不能排除缩进错误,因为它是在解析代码时引发的,而不是在运行时引发的。 try..except 块是在那个时间点不存在的运行时构造,因此它还不能做任何事情。

      如果您只是为了好奇而对捕获该异常感兴趣,您可以通过编写代码来实现这一目标,即当引发代码为 compiled explicitly 时异常处理就位:

      >>> try:
      ...     compile("""def foo():\nprint('bar')""", '<string>', 'exec')
      ... except IndentationError:
      ...     print('baz')
      ...     
      baz
      

      正如 DeepSpace 已经说过的,排除这样的错误没有什么意义,因为在运行时没有健全的方法来修复这种程序状态。

      【讨论】:

        【解决方案4】:

        只要解析器发现不遵循缩进规则的源代码,就会发生 IndentationError。 我们可以在导入模块时捕获它。 因为模块将在第一次导入时编译。你不能在包含 try/except 块的同一个模块中捕获它,因为有了这个异常,Python 将无法完成模块的编译,并且模块中的任何代码都不会运行。

        问题在于代码缩进。这会停止执行 python 脚本,因为它在同一个模块中。

        try:
           def Test():
              print("Test Function")
        except IndentationError:
           print("Exception raised")
        

        【讨论】:

        • "这不是例外,而是错误。"这并不完全正确,IndentationError 是Exception 的子类,它当然可以在运行时被捕获在一个 except 块中。他们的例子中的问题是他们没有进入运行时。
        • @Arne 更新答案。你可以通过here
        猜你喜欢
        • 2011-11-23
        • 2018-06-02
        • 2018-02-06
        • 2016-07-19
        • 1970-01-01
        • 2015-04-14
        • 2014-04-10
        • 2014-05-24
        • 1970-01-01
        相关资源
        最近更新 更多