请勿尝试为以下代码找到一些合理的解释。只是简单地重现案例。 问题是我得到了一个包含在另一个异常中的异常,而我只期待其中一个异常。 Python代码如下:
class TEST(object):
def __init__(self, param, content=[]):
self.param = param
self.content = content
def test_rec(self):
try:
collection = ''.join([c.test_rec() for c in self.content])
except Exception as e:
raise Exception('Exception [%s] in %s' % (e, self.__class__))
return collection+self.param
class TEST2(TEST):
pass
a = TEST('1')
b = TEST2('2')
c = TEST2('3')
a.content = [b, c]
b.content = 1
print a.test_rec()
目前的例外是:
Exception: Exception [Exception ['int' object is not iterable] in <class '__main__.TEST2'>] in <class '__main__.TEST'>
预期是:
Exception: Exception ['int' object is not iterable] in <class '__main__.TEST2'>
答案 0 :(得分:0)
当您添加其他打印语句时,您会看到会发生什么:
def test_rec(self):
try:
collection = ''.join([c.test_rec() for c in self.content])
except Exception as e:
print(e)
raise Exception('<%s> in %s' % (e, self.__class__))
return collection+self.param
print语句给出:
'int' object is not iterable
<'int' object is not iterable> in <class '__main__.TEST2'>
最后的例外是
Exception: <<'int' object is not iterable> in <class '__main__.TEST2'>> in <class '__main__.TEST'>
a.test_rec()
- &gt; b.test_rec()
;这引发了异常,抓住它并重新加注它。这反过来被a.test_rec()
抓住并重新加注。
答案 1 :(得分:0)
这是解决方案。有点难看,但它有效:
class MyException(Exception):
pass
class TEST(object):
def __init__(self, param, content=[]):
self.param = param
self.content = content
def test_rec(self):
try:
collection = ''.join([c.test_rec() for c in self.content])
except MyException:
raise
except Exception as e:
raise MyException('Exception [%s] in %s' % (e, self.__class__))
return collection+self.param
class TEST2(TEST):
pass
a = TEST('1')
b = TEST2('2')
c = TEST2('3')
a.content = [b, c]
b.content = 1
print a.test_rec()