title: Exception gets executed twice and it gets caught by a different except block
body: <p>I have the following code:</p>
  
  <p><strong>file1.py</strong></p>
  
  <pre><code>from file2 import tfun
  
  class TestException(Exception):
      pass
  
  try:
      print 'I am running'
      tfun()
  except TestException as e:
      print 'I am caught'
      print type(e)
  except Exception as e:
      print 'I am generally caught'
      print type(e)
  </code></pre>
  
  <p><strong>file2.py</strong></p>
  
  <pre><code>def tfun():
      from file1 import TestException
      raise TestException()
  </code></pre>
  
  <p>and the output from <code>python file1.py</code> is the following:</p>
  
  <pre><code>I am running
  I am running
  I am caught
  &lt;class 'file1.TestException'&gt;
  I am generally caught
  &lt;class 'file1.TestException'&gt;
  </code></pre>
  
  <p>First of all why the code gets executed twice in this case? I can understand that the import is recursive but why the code of the script get executed again?</p>
  
  <p>Secondly, the second time it is not getting caught by the same <code>except</code> block even though it is the same type as the first time, which also I cannot find an explanation for.</p>
  
  <p>Finally, I am trying to find a workaround for this problem without moving anything to a new file but I it does not seem to be any. Is it possible to get over this problem?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>For the second question I realized it is because the code is inside the module level.</p>