title: How do I use GeneratorExit?
body: <p>I have the following <a href="https://stackoverflow.com/help/mcve">mcve</a>:</p>
  
  <pre><code>import logging
  class MyGenIt(object):
      def __init__(self, name, content):
          self.name = name
          self.content = content
      def __iter__(self):
          with self:
              for o in self.content:
                  yield o
      def __enter__(self):
          return self
      def __exit__(self,  exc_type, exc_value, traceback):
          if exc_type:
              logging.error("Aborted %s", self,
                            exc_info=(exc_type, exc_value, traceback))
  </code></pre>
  
  <p>And here is sample use:</p>
  
  <pre><code>for x in MyGenIt("foo",range(10)):
      if x == 5:
          raise ValueError("got 5")
  </code></pre>
  
  <p>I would like <code>logging.error</code> to report the <code>ValueError</code>, but instead it reports <code>GeneratorExit</code>:</p>
  
  <pre><code>ERROR:root:Aborted &lt;__main__.MyGenIt object at 0x10ca8e350&gt;
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 8, in __iter__
  GeneratorExit
  </code></pre>
  
  <p>When I catch <code>GeneratorExit</code> in <code>__iter__</code>:</p>
  
  <pre><code>def __iter__(self):
      with self:
          try:
              for o in self.content:
                  yield o
          except GeneratorExit:
              return
  </code></pre>
  
  <p>nothing is logged (of course) because <code>__exit__</code> is called with <code>exc_type=None</code>. </p>
  
  <ol>
  <li>Why do I see <code>GeneratorExit</code> instead of <code>ValueError</code> in <code>__exit__</code>?</li>
  <li>What do I do to get the desired behavior, i.e., <code>ValueError</code> in <code>__exit__</code>?</li>
  </ol>