Raise an exception in python3 for this method which check dictionary.get with default value?
<p>I have a requirement that I have to raise an exception in method "meth(a)", only way I can achieve is to declare dictionary "a" to some value such that a.get('v', 0) raise an exception</p>

<pre class="lang-python prettyprint-override"><code>def meth(a):
    if isinstance(a, dict):
        return a.get('v', 0)# I have to raise an exception from here
    return 0

a = {} #I have to give some value into this dictionary so that my meth(a) raises an exception'''
import re
import sys
import traceback

try:
    meth(a)
except Exception:
    print("meth exception!")
    sys.exit()
    raise
else:
    sys.stderr.write("meth has no exception")
</code></pre>

<p>Depends on what you mean by <em>declare dictionary "a" to some value</em>. You can create your own class that inherits from <code>dict</code> so that the <code>isinstance</code> test works and implement an unfriendly <code>get</code>.</p>

<pre><code>class MyDict(dict):

    def get(self, name, default=None):
        raise NameError("No way am I getting you a value. "
            "What kind of a dict do you think I am?")

a = MyDict()
</code></pre>

<p>and the rest is just your program...</p>

python dictionary exception-handling default