title: Python -- efficiency of caught exceptions
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8107695/python-faq-how-fast-are-exceptions">Python FAQ: “How fast are exceptions?”</a>  </p>
  </blockquote>
  
  
  
  <p>I remember reading that Python implements a "Better to seek forgiveness than to ask permission" philosophy with regards to exceptions.  According to the author, this meant Python code should use a lot of try - except clauses, rather than trying to determine ahead of time if you were about to do something that would cause an exception.</p>
  
  <p>I just wrote some try - except clauses on my web app in which an exception will be raised most of the time the code is run.  So, in this case, raising and catching an exception will be the norm.  Is this bad from an efficiency point of view?  I also remember someone telling me that catching a raised exception has a large performance overhead.  </p>
  
  <p>Is it unnecessarily inefficient to use try - except clauses in which you expect an exception to be raised and caught almost all of the time?</p>
  
  <p>Here's the code -- its using the Django ORM to check for objects that associate users with various third party social providers.</p>
  
  <pre><code>try:
      fb_social_auth = UserSocialAuth.objects.get(user=self, provider='facebook')
      user_dict['facebook_id'] = fb_social_auth.uid
  except ObjectDoesNotExist:
      user_dict['facebook_id'] = None
  
  try:
      fs_social_auth = UserSocialAuth.objects.get(user=self, provider='foursquare')
      user_dict['foursquare_id'] = fs_social_auth.uid
  except ObjectDoesNotExist:
      user_dict['foursquare_id'] = None
  
  try:
      tw_social_auth = UserSocialAuth.objects.get(user=self, provider='twitter')
      user_dict['twitter_id'] = tw_social_auth.uid
  except ObjectDoesNotExist:
      user_dict['twitter_id'] = None
  </code></pre>
  
  <p>The first one will rarely take the exception, since right now we are enforcing "Sign In With Facebook" as the primary method for new users to join the site.  But, Twitter and Foursquare are optional, in case they want to import friends or followers, and I expect most people will not.</p>
  
  <p>I'm open to better ways to code this logic.</p>