Gan*_*ndi 10 python exception-handling indentation
首先 - 我对错误的代码没有问题,我知道这个异常是如何工作的.
我问,如果有任何方法在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任何意义?
NPE*_*NPE 12
是的,这可以做到.但是,被测功能必须存在于不同的模块中:
# test1.py
try:
import test2
except IndentationError as ex:
print ex
# test2.py
def f():
pass
pass # error
Run Code Online (Sandbox Code Playgroud)
运行时,这会正确捕获异常.在整个模块上立即进行检查是没有价值的; 我不确定是否有办法让它更精细.
IndentationError在编译模块时引发.您可以在导入模块时捕获它,因为模块将在首次导入时编译.你不能在包含它的同一个模块中捕获它try/except,因为使用它IndentationError,Python将无法完成对模块的编译,并且模块中不会运行任何代码.
| 归档时间: |
|
| 查看次数: |
1356 次 |
| 最近记录: |