相关疑难解决方法(0)

如何捕获IndentationError

首先 - 我对错误的代码没有问题,我知道这个异常是如何工作的.

我问,如果有任何方法在try/except块的代码中捕获IndentationError?例如,假设我正在为其他人编写的函数编写测试.我想在try/except块中运行它并处理他/她可以做出的所有警告.我知道,这不是一个最好的例子,但第一个出现在我脑海中.请不要专注于一个例子,而是关注问题.

我们来看看代码:

try:
    f()
except IndentationError:
    print "Error"

print "Finished"
Run Code Online (Sandbox Code Playgroud)

功能:

def f():
  print "External function"
Run Code Online (Sandbox Code Playgroud)

结果是:

External function
Finished
Run Code Online (Sandbox Code Playgroud)

这就是我已经准备好理解的东西,因为外部函数的缩进是一致的.

但是当函数看起来像这样:

def f():
  print "External function"
     print "with bad indentation"
Run Code Online (Sandbox Code Playgroud)

异常未处理:

    print "with bad indentation"
    ^
IndentationError: unexpected indent
Run Code Online (Sandbox Code Playgroud)

有没有办法实现它?我想这是编译的问题,到目前为止我看不到任何可能性.是否except IndentationError任何意义?

python exception-handling indentation

10
推荐指数
3
解决办法
1356
查看次数

标签 统计

exception-handling ×1

indentation ×1

python ×1