Commit ecc18276 authored by Hanno Schlichting's avatar Hanno Schlichting

Avoid bare except's.

parent ca5312b4
...@@ -35,7 +35,7 @@ class FuncCode: ...@@ -35,7 +35,7 @@ class FuncCode:
try: try:
return cmp((self.co_argcount, self.co_varnames), return cmp((self.co_argcount, self.co_varnames),
(other.co_argcount, other.co_varnames)) (other.co_argcount, other.co_varnames))
except: except Exception:
return 1 return 1
...@@ -182,7 +182,7 @@ def getObject(module, name, reload=0, ...@@ -182,7 +182,7 @@ def getObject(module, name, reload=0,
else: else:
try: try:
execsrc = open(path) execsrc = open(path)
except: except Exception:
raise NotFound("The specified module, '%s', " raise NotFound("The specified module, '%s', "
"couldn't be opened." % module) "couldn't be opened." % module)
module_dict = {} module_dict = {}
......
...@@ -107,7 +107,7 @@ class ImageFile(Explicit): ...@@ -107,7 +107,7 @@ class ImageFile(Explicit):
# of the way they parse it). # of the way they parse it).
try: try:
mod_since = int(DateTime(header).timeTime()) mod_since = int(DateTime(header).timeTime())
except: except Exception:
mod_since = None mod_since = None
if mod_since is not None: if mod_since is not None:
if getattr(self, 'lmt', None): if getattr(self, 'lmt', None):
......
...@@ -146,7 +146,7 @@ def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None): ...@@ -146,7 +146,7 @@ def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None):
if REQUEST is not None: if REQUEST is not None:
try: try:
u = self.DestinationURL() u = self.DestinationURL()
except: except Exception:
u = REQUEST['URL1'] u = REQUEST['URL1']
if submit == " Add and Edit ": if submit == " Add and Edit ":
u = "%s/%s" % (u, quote(id)) u = "%s/%s" % (u, quote(id))
......
...@@ -306,7 +306,7 @@ def addDTMLMethod(self, id, title='', file='', REQUEST=None, submit=None): ...@@ -306,7 +306,7 @@ def addDTMLMethod(self, id, title='', file='', REQUEST=None, submit=None):
if REQUEST is not None: if REQUEST is not None:
try: try:
u = self.DestinationURL() u = self.DestinationURL()
except: except Exception:
u = REQUEST['URL1'] u = REQUEST['URL1']
if submit == " Add and Edit ": if submit == " Add and Edit ":
u = "%s/%s" % (u, quote(id)) u = "%s/%s" % (u, quote(id))
......
...@@ -118,7 +118,7 @@ class LockableItem(EtagSupport): ...@@ -118,7 +118,7 @@ class LockableItem(EtagSupport):
try: try:
locks = self.wl_lockmapping() locks = self.wl_lockmapping()
locks.clear() locks.clear()
except: except Exception:
# The locks may be totally messed up, so we'll just delete # The locks may be totally messed up, so we'll just delete
# and replace. # and replace.
if hasattr(self, '_dav_writelocks'): if hasattr(self, '_dav_writelocks'):
......
...@@ -396,7 +396,7 @@ class ObjectManager(CopyContainer, ...@@ -396,7 +396,7 @@ class ObjectManager(CopyContainer,
# on Broken objects. # on Broken objects.
try: try:
ob._v__object_deleted__ = 1 ob._v__object_deleted__ = 1
except: except Exception:
pass pass
if not suppress_events: if not suppress_events:
...@@ -524,7 +524,7 @@ class ObjectManager(CopyContainer, ...@@ -524,7 +524,7 @@ class ObjectManager(CopyContainer,
raise BadRequest('No items specified') raise BadRequest('No items specified')
try: try:
p = self._reserved_names p = self._reserved_names
except: except Exception:
p = () p = ()
for n in ids: for n in ids:
if n in p: if n in p:
...@@ -645,7 +645,7 @@ class ObjectManager(CopyContainer, ...@@ -645,7 +645,7 @@ class ObjectManager(CopyContainer,
# the error. # the error.
try: try:
stat = marshal.loads(v.manage_FTPstat(REQUEST)) stat = marshal.loads(v.manage_FTPstat(REQUEST))
except: except Exception:
LOG.error("Failed to stat file '%s'" % k, LOG.error("Failed to stat file '%s'" % k,
exc_info=sys.exc_info()) exc_info=sys.exc_info())
stat = None stat = None
......
...@@ -202,7 +202,7 @@ class Item(Base, ...@@ -202,7 +202,7 @@ class Item(Base,
if not error_message: if not error_message:
try: try:
s = ustr(error_value) s = ustr(error_value)
except: except Exception:
s = error_value s = error_value
try: try:
match = tagSearch(s) match = tagSearch(s)
...@@ -236,14 +236,14 @@ class Item(Base, ...@@ -236,14 +236,14 @@ class Item(Base,
v = s(**kwargs) v = s(**kwargs)
else: else:
v = HTML.__call__(s, client, REQUEST, **kwargs) v = HTML.__call__(s, client, REQUEST, **kwargs)
except: except Exception:
logger.error( logger.error(
'Exception while rendering an error message', 'Exception while rendering an error message',
exc_info=True exc_info=True
) )
try: try:
strv = repr(error_value) # quotes tainted strings strv = repr(error_value) # quotes tainted strings
except: except Exception:
strv = ('<unprintable %s object>' % strv = ('<unprintable %s object>' %
str(type(error_value).__name__)) str(type(error_value).__name__))
v = strv + ( v = strv + (
...@@ -360,7 +360,7 @@ class Item(Base, ...@@ -360,7 +360,7 @@ class Item(Base,
""" """
try: try:
path = '/'.join(self.getPhysicalPath()) path = '/'.join(self.getPhysicalPath())
except: except Exception:
return Base.__repr__(self) return Base.__repr__(self)
context_path = None context_path = None
context = aq_parent(self) context = aq_parent(self)
...@@ -368,7 +368,7 @@ class Item(Base, ...@@ -368,7 +368,7 @@ class Item(Base,
if aq_base(context) is not aq_base(container): if aq_base(context) is not aq_base(container):
try: try:
context_path = '/'.join(context.getPhysicalPath()) context_path = '/'.join(context.getPhysicalPath())
except: except Exception:
context_path = None context_path = None
res = '<%s' % self.__class__.__name__ res = '<%s' % self.__class__.__name__
res += ' at %s' % path res += ' at %s' % path
......
...@@ -346,7 +346,7 @@ class Traversable: ...@@ -346,7 +346,7 @@ class Traversable:
except ConflictError: except ConflictError:
raise raise
except: except Exception:
if default is not _marker: if default is not _marker:
return default return default
else: else:
......
...@@ -118,7 +118,7 @@ class RoleManager(BaseRoleManager): ...@@ -118,7 +118,7 @@ class RoleManager(BaseRoleManager):
if not have('acquire_%s' % permission_hash): if not have('acquire_%s' % permission_hash):
roles = tuple(roles) roles = tuple(roles)
p.setRoles(roles) p.setRoles(roles)
except: except Exception:
fails.append(name) fails.append(name)
if fails: if fails:
...@@ -196,7 +196,7 @@ class RoleManager(BaseRoleManager): ...@@ -196,7 +196,7 @@ class RoleManager(BaseRoleManager):
for role in roles: for role in roles:
try: try:
data.remove(role) data.remove(role)
except: except Exception:
pass pass
self.__ac_roles__ = tuple(data) self.__ac_roles__ = tuple(data)
if REQUEST is not None: if REQUEST is not None:
......
...@@ -163,7 +163,7 @@ def callManageBeforeDelete(ob, item, container): ...@@ -163,7 +163,7 @@ def callManageBeforeDelete(ob, item, container):
raise raise
except ConflictError: except ConflictError:
raise raise
except: except Exception:
LOG.error('_delObject() threw', exc_info=True) LOG.error('_delObject() threw', exc_info=True)
# In debug mode when non-Manager, let exceptions propagate. # In debug mode when non-Manager, let exceptions propagate.
if getConfiguration().debug_mode: if getConfiguration().debug_mode:
......
...@@ -80,7 +80,7 @@ class TestGetAttr(unittest.TestCase): ...@@ -80,7 +80,7 @@ class TestGetAttr(unittest.TestCase):
self.folder._setObject('denied', DeniedItem()) self.folder._setObject('denied', DeniedItem())
self.folder._setObject('protected', ProtectedItem()) self.folder._setObject('protected', ProtectedItem())
except: except Exception:
self.tearDown() self.tearDown()
raise raise
......
...@@ -76,7 +76,7 @@ class CopySupportTestBase(unittest.TestCase): ...@@ -76,7 +76,7 @@ class CopySupportTestBase(unittest.TestCase):
# has one. We use a subtransaction, which means we can rollback # has one. We use a subtransaction, which means we can rollback
# later and pretend we didn't touch the ZODB. # later and pretend we didn't touch the ZODB.
transaction.commit() transaction.commit()
except: except Exception:
self.connection.close() self.connection.close()
raise raise
transaction.begin() transaction.begin()
......
...@@ -84,7 +84,7 @@ class EventTest(unittest.TestCase): ...@@ -84,7 +84,7 @@ class EventTest(unittest.TestCase):
uf._doAddUser('manager', 'secret', ['Manager'], []) uf._doAddUser('manager', 'secret', ['Manager'], [])
user = uf.getUserById('manager').__of__(uf) user = uf.getUserById('manager').__of__(uf)
newSecurityManager(None, user) newSecurityManager(None, user)
except: except Exception:
self.tearDown() self.tearDown()
raise raise
......
...@@ -94,7 +94,7 @@ class HookTest(unittest.TestCase): ...@@ -94,7 +94,7 @@ class HookTest(unittest.TestCase):
uf._doAddUser('manager', 'secret', ['Manager'], []) uf._doAddUser('manager', 'secret', ['Manager'], [])
user = uf.getUserById('manager').__of__(uf) user = uf.getUserById('manager').__of__(uf)
newSecurityManager(None, user) newSecurityManager(None, user)
except: except Exception:
self.tearDown() self.tearDown()
raise raise
......
...@@ -24,11 +24,7 @@ from zope.component import adapter ...@@ -24,11 +24,7 @@ from zope.component import adapter
from zope.lifecycleevent.interfaces import IObjectModifiedEvent from zope.lifecycleevent.interfaces import IObjectModifiedEvent
from zope.lifecycleevent.interfaces import IObjectCreatedEvent from zope.lifecycleevent.interfaces import IObjectCreatedEvent
try: here = os.path.dirname(os.path.abspath(__file__))
here = os.path.dirname(os.path.abspath(__file__))
except:
here = os.path.dirname(os.path.abspath(sys.argv[0]))
imagedata = os.path.join(here, 'test.gif') imagedata = os.path.join(here, 'test.gif')
filedata = os.path.join(here, 'test.gif') filedata = os.path.join(here, 'test.gif')
...@@ -107,7 +103,7 @@ class FileTests(unittest.TestCase): ...@@ -107,7 +103,7 @@ class FileTests(unittest.TestCase):
# Hack, we need a _p_mtime for the file, so we make sure that it # Hack, we need a _p_mtime for the file, so we make sure that it
# has one. # has one.
transaction.commit() transaction.commit()
except: except Exception:
self.connection.close() self.connection.close()
raise raise
transaction.begin() transaction.begin()
......
...@@ -78,7 +78,7 @@ class TestRequestRange(unittest.TestCase): ...@@ -78,7 +78,7 @@ class TestRequestRange(unittest.TestCase):
# has one. We use a subtransaction, which means we can rollback # has one. We use a subtransaction, which means we can rollback
# later and pretend we didn't touch the ZODB. # later and pretend we didn't touch the ZODB.
transaction.commit() transaction.commit()
except: except Exception:
self.connection.close() self.connection.close()
raise raise
......
...@@ -111,7 +111,7 @@ class TestSimpleItem(unittest.TestCase): ...@@ -111,7 +111,7 @@ class TestSimpleItem(unittest.TestCase):
try: try:
raise BadRequest("1") raise BadRequest("1")
except: except Exception:
item.raise_standardErrorMessage(client=item, item.raise_standardErrorMessage(client=item,
REQUEST=REQUEST()) REQUEST=REQUEST())
......
...@@ -241,7 +241,7 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager, ...@@ -241,7 +241,7 @@ class BasicUserFolder(Navigation, Tabs, Item, RoleManager,
if item is self: if item is self:
try: try:
del container.__allow_groups__ del container.__allow_groups__
except: except Exception:
pass pass
def manage_afterAdd(self, item, container): def manage_afterAdd(self, item, container):
...@@ -290,7 +290,7 @@ class UserFolder(accesscontrol_userfolder.UserFolder, BasicUserFolder): ...@@ -290,7 +290,7 @@ class UserFolder(accesscontrol_userfolder.UserFolder, BasicUserFolder):
cfg = App.config.getConfiguration() cfg = App.config.getConfiguration()
try: try:
os.remove(os.path.join(cfg.instancehome, 'inituser')) os.remove(os.path.join(cfg.instancehome, 'inituser'))
except: except Exception:
pass pass
InitializeClass(UserFolder) InitializeClass(UserFolder)
......
...@@ -278,7 +278,7 @@ class view(zope.browserpage.metaconfigure.view): ...@@ -278,7 +278,7 @@ class view(zope.browserpage.metaconfigure.view):
try: try:
cname = str(name) cname = str(name)
except: except Exception:
cname = "GeneratedClass" cname = "GeneratedClass"
cdict['__name__'] = name cdict['__name__'] = name
......
...@@ -92,7 +92,7 @@ class PageTemplate(ExtensionClass.Base, ...@@ -92,7 +92,7 @@ class PageTemplate(ExtensionClass.Base,
return err return err
try: try:
self.pt_render(source=True, extra_context=namespace) self.pt_render(source=True, extra_context=namespace)
except: except Exception:
return ('Macro expansion failed', '%s: %s' % sys.exc_info()[:2]) return ('Macro expansion failed', '%s: %s' % sys.exc_info()[:2])
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
...@@ -107,7 +107,7 @@ class PageTemplate(ExtensionClass.Base, ...@@ -107,7 +107,7 @@ class PageTemplate(ExtensionClass.Base,
return self._text return self._text
try: try:
return self.pt_render(source=True) return self.pt_render(source=True)
except: except Exception:
return ('%s\n Macro expansion failed\n %s\n-->\n%s' % return ('%s\n Macro expansion failed\n %s\n-->\n%s' %
(self._error_start, "%s: %s" % sys.exc_info()[:2], (self._error_start, "%s: %s" % sys.exc_info()[:2],
self._text)) self._text))
......
...@@ -154,7 +154,7 @@ class PageTemplateFile(SimpleItem, Script, PageTemplate, Traversable): ...@@ -154,7 +154,7 @@ class PageTemplateFile(SimpleItem, Script, PageTemplate, Traversable):
f = open(self.filename, "rb") f = open(self.filename, "rb")
try: try:
text = f.read(XML_PREFIX_MAX_LENGTH) text = f.read(XML_PREFIX_MAX_LENGTH)
except: except Exception:
f.close() f.close()
raise raise
t = sniff_type(text) t = sniff_type(text)
......
...@@ -328,7 +328,7 @@ class ZopePageTemplate(Script, PageTemplate, Cacheable, ...@@ -328,7 +328,7 @@ class ZopePageTemplate(Script, PageTemplate, Cacheable,
"""Returns a file name to be compiled into the TAL code.""" """Returns a file name to be compiled into the TAL code."""
try: try:
return '/'.join(self.getPhysicalPath()) return '/'.join(self.getPhysicalPath())
except: except Exception:
# This page template is being compiled without an # This page template is being compiled without an
# acquisition context, so we don't know where it is. :-( # acquisition context, so we don't know where it is. :-(
return None return None
......
...@@ -29,7 +29,7 @@ default_encoding = sys.getdefaultencoding() ...@@ -29,7 +29,7 @@ default_encoding = sys.getdefaultencoding()
class DefaultUnicodeEncodingConflictResolver(object): class DefaultUnicodeEncodingConflictResolver(object):
""" This resolver implements the old-style behavior and will """ This resolver implements the old-style behavior and will
raise an exception in case of the string 'text' can't be converted raise an exception in case of the string 'text' can't be converted
propertly to unicode. properly to unicode.
""" """
implements(IUnicodeEncodingConflictResolver) implements(IUnicodeEncodingConflictResolver)
......
...@@ -59,7 +59,7 @@ class PortalTestCase(base.TestCase): ...@@ -59,7 +59,7 @@ class PortalTestCase(base.TestCase):
self.portal = self._portal() self.portal = self._portal()
self._setup() self._setup()
self.afterSetUp() self.afterSetUp()
except: except Exception:
self._clear() self._clear()
raise raise
......
...@@ -85,7 +85,7 @@ class ZopeTestCase(base.TestCase): ...@@ -85,7 +85,7 @@ class ZopeTestCase(base.TestCase):
try: try:
if connections.contains(self.app): if connections.contains(self.app):
self.app._delObject(folder_name) self.app._delObject(folder_name)
except: except Exception:
pass pass
base.TestCase._clear(self, call_close_hook) base.TestCase._clear(self, call_close_hook)
......
...@@ -90,7 +90,7 @@ class TestCase(unittest.TestCase, object): ...@@ -90,7 +90,7 @@ class TestCase(unittest.TestCase, object):
self.app = self._app() self.app = self._app()
self._setup() self._setup()
self.afterSetUp() self.afterSetUp()
except: except Exception:
self._clear() self._clear()
raise raise
...@@ -101,7 +101,7 @@ class TestCase(unittest.TestCase, object): ...@@ -101,7 +101,7 @@ class TestCase(unittest.TestCase, object):
try: try:
self.beforeTearDown() self.beforeTearDown()
self._clear(1) self._clear(1)
except: except Exception:
self._clear() self._clear()
raise raise
......
...@@ -191,7 +191,7 @@ class TestTestCase(HookTest): ...@@ -191,7 +191,7 @@ class TestTestCase(HookTest):
class TestSetUpRaises(HookTest): class TestSetUpRaises(HookTest):
class Error: class Error(Exception):
pass pass
def setUp(self): def setUp(self):
...@@ -212,7 +212,7 @@ class TestSetUpRaises(HookTest): ...@@ -212,7 +212,7 @@ class TestSetUpRaises(HookTest):
class TestTearDownRaises(HookTest): class TestTearDownRaises(HookTest):
class Error: class Error(Exception):
pass pass
def tearDown(self): def tearDown(self):
......
...@@ -493,7 +493,7 @@ class HookTest(ZopeTestCase.PortalTestCase): ...@@ -493,7 +493,7 @@ class HookTest(ZopeTestCase.PortalTestCase):
class TestSetUpRaises(HookTest): class TestSetUpRaises(HookTest):
class Error: class Error(Exception):
pass pass
def getPortal(self): def getPortal(self):
......
...@@ -678,7 +678,7 @@ class HTTPRequest(BaseRequest): ...@@ -678,7 +678,7 @@ class HTTPRequest(BaseRequest):
if not is_tainted: if not is_tainted:
tainted = None tainted = None
except: except Exception:
if (not item and not (flags & DEFAULT) and if (not item and not (flags & DEFAULT) and
key in defaults): key in defaults):
item = defaults[key] item = defaults[key]
...@@ -1605,7 +1605,7 @@ def sane_environment(env): ...@@ -1605,7 +1605,7 @@ def sane_environment(env):
dict['HTTP_AUTHORIZATION'] = dict['HTTP_CGI_AUTHORIZATION'] dict['HTTP_AUTHORIZATION'] = dict['HTTP_CGI_AUTHORIZATION']
try: try:
del dict['HTTP_CGI_AUTHORIZATION'] del dict['HTTP_CGI_AUTHORIZATION']
except: except Exception:
pass pass
return dict return dict
......
...@@ -876,7 +876,7 @@ class HTTPResponse(HTTPBaseResponse): ...@@ -876,7 +876,7 @@ class HTTPResponse(HTTPBaseResponse):
b = str(b) b = str(b)
except UnicodeEncodeError: except UnicodeEncodeError:
b = self._encode_unicode(unicode(b)) b = self._encode_unicode(unicode(b))
except: except Exception:
b = '<unprintable %s object>' % type(b).__name__ b = '<unprintable %s object>' % type(b).__name__
if fatal and t is SystemExit and v.code == 0: if fatal and t is SystemExit and v.code == 0:
......
...@@ -18,5 +18,5 @@ def ClassFactory(jar, module, name, _silly=('__doc__',), _globals={}): ...@@ -18,5 +18,5 @@ def ClassFactory(jar, module, name, _silly=('__doc__',), _globals={}):
try: try:
m = __import__(module, _globals, _globals, _silly) m = __import__(module, _globals, _globals, _silly)
return getattr(m, name) return getattr(m, name)
except: except Exception:
return OFS.Uninstalled.Broken(jar, None, (module, name)) return OFS.Uninstalled.Broken(jar, None, (module, name))
...@@ -87,7 +87,7 @@ def startup(): ...@@ -87,7 +87,7 @@ def startup():
# Try to use custom storage # Try to use custom storage
try: try:
m = imp.find_module('custom_zodb', [configuration.testinghome]) m = imp.find_module('custom_zodb', [configuration.testinghome])
except: except Exception:
m = imp.find_module('custom_zodb', [configuration.instancehome]) m = imp.find_module('custom_zodb', [configuration.instancehome])
except Exception: except Exception:
# if there is no custom_zodb, use the config file specified databases # if there is no custom_zodb, use the config file specified databases
......
...@@ -61,7 +61,7 @@ class WSGIStarter(object): ...@@ -61,7 +61,7 @@ class WSGIStarter(object):
if locale_id is not None: if locale_id is not None:
try: try:
import locale import locale
except: except Exception:
raise ConfigurationError( raise ConfigurationError(
'The locale module could not be imported.\n' 'The locale module could not be imported.\n'
'To use localization options, you must ensure\n' 'To use localization options, you must ensure\n'
...@@ -69,7 +69,7 @@ class WSGIStarter(object): ...@@ -69,7 +69,7 @@ class WSGIStarter(object):
'Python installation.') 'Python installation.')
try: try:
locale.setlocale(locale.LC_ALL, locale_id) locale.setlocale(locale.LC_ALL, locale_id)
except: except Exception:
raise ConfigurationError( raise ConfigurationError(
'The specified locale "%s" is not supported by your' 'The specified locale "%s" is not supported by your'
'system.\nSee your operating system documentation for ' 'system.\nSee your operating system documentation for '
......
...@@ -110,7 +110,7 @@ def main(): ...@@ -110,7 +110,7 @@ def main():
sys.exit(2) sys.exit(2)
try: try:
uid = int(arg) uid = int(arg)
except: except Exception:
try: try:
import pwd import pwd
uid = pwd.getpwnam(arg)[2] uid = pwd.getpwnam(arg)[2]
...@@ -135,7 +135,7 @@ def main(): ...@@ -135,7 +135,7 @@ def main():
sys.exit(2) sys.exit(2)
try: try:
gid = int(arg) gid = int(arg)
except: except Exception:
try: try:
import pwd import pwd
gid = pwd.getpwnam(arg)[3] gid = pwd.getpwnam(arg)[3]
......
...@@ -186,10 +186,7 @@ def get_inituser(): ...@@ -186,10 +186,7 @@ def get_inituser():
def write_inituser(fn, user, password): def write_inituser(fn, user, password):
import binascii import binascii
try: from hashlib import sha1 as sha
from hashlib import sha1 as sha
except:
from sha import new as sha
fp = open(fn, "w") fp = open(fn, "w")
pw = binascii.b2a_base64(sha(password).digest())[:-1] pw = binascii.b2a_base64(sha(password).digest())[:-1]
fp.write('%s:{SHA}%s\n' % (user, pw)) fp.write('%s:{SHA}%s\n' % (user, pw))
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment