如何捕获IndentationError [英] How to catch IndentationError

查看:206
本文介绍了如何捕获IndentationError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我没有错误的代码的问题,我有一个想法,这个异常如何工作。



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



我们来看看代码:



<$

$ b除了IndentationError:
打印错误

打印已完成

功能:

  def f():
print外部函数

结果是: / p>

 外部函数
已完成

这是一件事,我准备好了解,因为外部函数中的缩进一致。



但是当函数看起来像:

  def f():
print外部函数
printwith bad indentation

异常是未处理的:

  printwith bad indentation
^
IndentationError:unexpected indent

有没有办法实现它?我想这是编译的问题,至今我看不到有任何可能的抓住。

解决方案

是的,这可以做完了。但是,被测函数必须生活在不同的模块中:

 #test1.py 
try:
import test2
除了indentationError作为例如:
print ex

#test2.py
def f():
pass
pass#error

运行时,正确地捕获异常。在整个模块上一次完成检查是不值得的;我不知道有没有办法让它更细致。


First of all - I don't have a problem with bad-indentated code and I have an idea of how does this exception works like.

I ask, if there is any way to catch IndentationError in code with a try/except block? For example, let's say I'm writing a test for a function written by someone else. I want to run it in try/except block and handle all warning he/she could make. I know, that it's not a best example, but the first one coming to my mind. Please, don't focus on an example, but rather on problem.

Let's look at the code:

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

print "Finished"

The function:

def f():
  print "External function"

And the result is:

External function
Finished

And that's something, I'm ready to understand, becouse indentation in external function was consistant.

But when the function look like that:

def f():
  print "External function"
     print "with bad indentation"

The exception is unhandled:

    print "with bad indentation"
    ^
IndentationError: unexpected indent

Is there any way to achieve it? I guess that's the matter of compiling, and as far I don't see any possibility to catch. Does the except IndentationError make any sense?

解决方案

Yes, this can be done. However, the function under test would have to live in a different module:

# test1.py
try:
    import test2
except IndentationError as ex:
    print ex

# test2.py
def f():
    pass
        pass # error

When run, this correctly catches the exception. It is worth nothing that the checking is done on the entire module at once; I am not sure if there's a way to make it more fine-grained.

这篇关于如何捕获IndentationError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆