[python-win32] Avoid bare except

Bill Janssen janssen at parc.com
Fri Oct 15 18:47:23 CEST 2010


Aahz <aahz at pythoncraft.com> wrote:

> On Thu, Oct 14, 2010, Bill Janssen wrote:
> > 
> > try:
> >     import win32api, win32security
> > 
> >     username = win32api.GetUserNameEx(win32api.NameSamCompatible)
> >     print 'granting "logon as a service" rights to ' + username
> >     policy_handle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS)
> >     sid_obj, domain, tmp = win32security.LookupAccountName(None, username)
> >     win32security.LsaAddAccountRights( policy_handle, sid_obj, ('SeServiceLogonRight',) )
> >     win32security.LsaClose( policy_handle )
> > except:
> >     print 'Exception granting user the SeServiceLogonRight:'
> >     print ''.join(traceback.format_exception(*sys.exc_info()))
> 
> Bill, I know you know this and are just being sloppy in a test script,
> but I figure we probably have some Python newcomers on this list:
> 
> Do *NOT* use bare except: clauses.  At the very least, that means you
> won't properly handle KeyboardInterrupt.  Always try to catch the
> specific exceptions you're expecting.  For more info, see
> 
> http://docs.python.org/howto/doanddont.html

Indeed.  Catching all exceptions is usually a bad idea, unless you're
trying to get some idea of what to expect, in which case you almost
always want to print out the actual exception.

> It also would have been easier to just use traceback.format_exc() unless
> you're stuck with Python less than 2.4.

Actually, that one I didn't know.  I was on 2.3.5 for too long, I guess.
Good tip, thanks!

Bill


More information about the python-win32 mailing list