Search code examples
pythondictionaryerror-handlingraise

Print lines after raising exception


Is there a way to print out the contents of a dictionary after raising an exception?

Assuming that the dictionary is this,

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

I would like it to look something like this:

---------------------------------------------------------------------------
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

Is this possible?


Solution

  • Append the dictionary to the exception message.

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