打印引发异常后的行



是否有一种方法可以在引发异常后打印出字典的内容?

假设字典是这样的,

d = {"orange":[1,2], "yellow":[5], "red":[2,6,7]}

我希望它看起来像这样:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-63-719ba08e2a6c> in <module>
----> 1 raise TypeError("This is a TypeError. Printing out contents of dictionary...")
TypeError: This is a TypeError.
orange
1
2
yellow
5
red
2
6
7

这可能吗?

将字典附加到异常消息中。

raise TypeError("This is a TypeError. Printing out contents of dictionary...n" + str(d))

格式不正确,但可以解决问题。

d = {"orange":[1,2], "yellow":[5], "red":[2,6,7]}
try:
d["melon"]
except:
raise Exception(f"{str(d)}")

或者你可以这样做:

try:
d["melon"]
except:
for k in d.keys():
print(k, d[k])
try:
# code here
except Exception as e:
# Try and replace `Exception` with the error you're getting
print(f"Error = {e}")
for name, val in zip(d.keys(), d.values()):
print(name)
for i in val:
print(i)

请注意,对于except Exception:,try循环将除了任何误差

相关内容

  • 没有找到相关文章

最新更新