Search code examples
pythonexceptiontry-exceptraise

raising error does not prevent try-except clause to get executed?


I've got surprised while testing a piece of code that looked a bit like that:

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)

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?


Solution

  • When you say except Exception, e:, you are explicitly catching (almost) any exception that might get raised within that block -- including your NotFound.

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

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

    try:
      # .. do stuff
      if blah:
        raise NotFound(...)
    except NotFound, e: 
      # print something
      raise
    

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