raising error does not prevent try-except clause to get executed?
<p>I've got surprised while testing a piece of code that looked a bit like that:</p>

<pre><code>if x:
    try:
           obj = look-for-item-with-id==x in a db
           if obj is None:
               # print debug message 
               raise NotFound('No item with this id')
           return obj
    except Exception, e:
        raise Error(e.message)
</code></pre>

<p>I expected that if there was no item with a provided id (x) in a db, the NotFound exception would be raised. But instead, after getting to if clause and  printing debug message it gets to the except clause and raises the Exception (exc message is Item not found...). Could someone be so kind and enlighten me here?</p>

<p>When you say <code>except Exception, e:</code>, you are explicitly catching (almost) <em>any</em> exception that might get raised within that block -- including your <code>NotFound</code>. </p>

<p>If you want the <code>NotFound</code> itself to propagate further up, you don't need to have a <code>try/except</code> block at all.</p>

<p>Alternatively, if you want to do something specific when you detect the <code>NotFound</code> but then continue propagating the same exception, you can use a blank <code>raise</code> statement to re-raise it instead of raising a new exception like you're doing; something like:</p>

<pre><code>try:
  # .. do stuff
  if blah:
    raise NotFound(...)
except NotFound, e: 
  # print something
  raise
</code></pre>

<p>Also note that I've changed the exception block to <code>except NotFound</code> -- it's generally not a good idea to use <code>except Exception</code> because it catches everything, which can hide errors you may not have expected. Basically, you want to use <code>except</code> to catch  <em>specific</em> things which you know how to handle right there.  </p>

python exception try-except raise