title: catch PIL exceptions in Tornado
body: <p>Catching errors dont works partialy!</p>
  
  <p>What I want to do is to detect if the user uploads real pictures or forged ones <em>(for example a text file renamed to <code>.jpeg</code>)</em>.</p>
  
  <pre><code>try:
      image = Image.open(StringIO.StringIO(buf=avat))
      type = image.format
      (x, y) = image.size
      print x, y
      if x &lt; y:
          orientation = "portrait"
      else:
          orientation = "paysage" 
      pref = str(time.time())
      nomf = pref.replace(".", "") 
      nomfich = nomf+"."+type
      self.fs = GridFS(self.db)
      avatar_id = self.fs.put(avat, content_type=avctype, filename=nomfich)
  except IOError, TypeError:
      self.redirect("/erreur-im")
  </code></pre>
  
  <p>Here is the taceball shown in <code>http://localhost:8000/erreur-im</code></p>
  
  <pre><code>Traceback (most recent call last):
    File "C:\Python27\lib\site-packages\tornado-2.3.post1-py2.7.egg\tornado\web.py", line 1023, in _execute
      getattr(self, self.request.method.lower())(*args, **kwargs)
    File "G:\Mon projet\sog-emouk\handlers.py", line 101, in get
      avctype = self.db.users.find_one()["avctype"]
  TypeError: 'NoneType' object has no attribute '__getitem__'
  </code></pre>
  
  <p>Here, I wanted to do is redirect users to a page to tell them that the user must use image picture.</p>
  
  <p>and when I've changed <code>self.redirect</code> to <code>self.write("please upload....")</code> the result was bizarre:</p>
  
  <pre><code>Traceback (most recent call last):
    File "C:\Python27\lib\site-packages\tornado-2.3.post1-py2.7.egg\tornado\web.py", line 1023, in _execute
      getattr(self, self.request.method.lower())(*args, **kwargs)
    File "G:\Mon projet\sog-emouk\handlers.py", line 153, in post
      user={"pseudo":pseudo, "orientation":orientation, "avctype":avctype, "password":password, "email":email, "tel":tel, "commune":commune, "coord":coord, "statut":statut, "telf":telf, "avatar":avatar_id, "acheteur":[], "vendeur":[]}
  UnboundLocalError: local variable 'orientation' referenced before assignment
  </code></pre>
  
  <p>So, I guess that <code>self.redirect</code> has something strange here since <code>self.write</code> excecutes the code after catching the exception <em>(indeed the image.size is not known due to text file)</em>.`</p>