[thorstenp] fix empty exception clauses

This commit is contained in:
Yann Leboulanger 2008-12-03 21:37:05 +00:00
parent f0dce41ab6
commit 3392c54dd0
14 changed files with 88 additions and 48 deletions

View File

@ -2333,7 +2333,7 @@ class ConnectionHandlers(ConnectionVcard, ConnectionBytestream, ConnectionDisco,
for jid in raw_roster: for jid in raw_roster:
try: try:
j = helpers.parse_jid(jid) j = helpers.parse_jid(jid)
except: except Exception:
print >> sys.stderr, _('JID %s is not RFC compliant. It will not be added to your roster. Use roster management tools such as http://jru.jabberstudio.org/ to remove it') % jid print >> sys.stderr, _('JID %s is not RFC compliant. It will not be added to your roster. Use roster management tools such as http://jru.jabberstudio.org/ to remove it') % jid
else: else:
infos = raw_roster[jid] infos = raw_roster[jid]

View File

@ -27,7 +27,7 @@ try:
from docutils.parsers.rst import roles from docutils.parsers.rst import roles
from docutils import nodes,utils from docutils import nodes,utils
from docutils.parsers.rst.roles import set_classes from docutils.parsers.rst.roles import set_classes
except: except ImportError:
print "Requires docutils 0.4 for set_classes to be available" print "Requires docutils 0.4 for set_classes to be available"
def create_xhtml(text): def create_xhtml(text):
return None return None

View File

@ -161,8 +161,10 @@ class SASL(PlugIn):
if challenge.getNamespace()!=NS_SASL: return if challenge.getNamespace()!=NS_SASL: return
if challenge.getName()=='failure': if challenge.getName()=='failure':
self.startsasl='failure' self.startsasl='failure'
try: reason=challenge.getChildren()[0] try:
except: reason=challenge reason=challenge.getChildren()[0]
except Exception:
reason=challenge
self.DEBUG('Failed SASL authentification: %s'%reason,'error') self.DEBUG('Failed SASL authentification: %s'%reason,'error')
raise NodeProcessed raise NodeProcessed
elif challenge.getName()=='success': elif challenge.getName()=='success':

View File

@ -149,7 +149,8 @@ def getPrivacyLists(disp):
if list_.getName()=='list': dict_['lists'].append(list_.getAttr('name')) if list_.getName()=='list': dict_['lists'].append(list_.getAttr('name'))
else: dict_[list_.getName()]=list_.getAttr('name') else: dict_[list_.getName()]=list_.getAttr('name')
return dict_ return dict_
except: pass except Exception:
pass
def getPrivacyList(disp,listname): def getPrivacyList(disp,listname):
""" Requests specific privacy list listname. Returns list of XML nodes (rules) """ Requests specific privacy list listname. Returns list of XML nodes (rules)
@ -157,7 +158,8 @@ def getPrivacyList(disp,listname):
try: try:
resp=disp.SendAndWaitForResponse(Iq('get',NS_PRIVACY,payload=[Node('list',{'name':listname})])) resp=disp.SendAndWaitForResponse(Iq('get',NS_PRIVACY,payload=[Node('list',{'name':listname})]))
if isResultNode(resp): return resp.getQueryPayload()[0] if isResultNode(resp): return resp.getQueryPayload()[0]
except: pass except Exception:
pass
def setActivePrivacyList(disp,listname=None,typ='active'): def setActivePrivacyList(disp,listname=None,typ='active'):
""" Switches privacy list 'listname' to specified type. """ Switches privacy list 'listname' to specified type.

View File

@ -69,8 +69,10 @@ class IBB(PlugIn):
err=None err=None
sid,blocksize=stanza.getTagAttr('open','sid'),stanza.getTagAttr('open','block-size') sid,blocksize=stanza.getTagAttr('open','sid'),stanza.getTagAttr('open','block-size')
self.DEBUG('StreamOpenHandler called sid->%s blocksize->%s'%(sid,blocksize),'info') self.DEBUG('StreamOpenHandler called sid->%s blocksize->%s'%(sid,blocksize),'info')
try: blocksize=int(blocksize) try:
except: err=ERR_BAD_REQUEST blocksize=int(blocksize)
except Exception:
err=ERR_BAD_REQUEST
if not sid or not blocksize: err=ERR_BAD_REQUEST if not sid or not blocksize: err=ERR_BAD_REQUEST
elif sid in self._streams.keys(): err=ERR_UNEXPECTED_REQUEST elif sid in self._streams.keys(): err=ERR_UNEXPECTED_REQUEST
if err: rep=Error(stanza,err) if err: rep=Error(stanza,err)
@ -137,8 +139,12 @@ class IBB(PlugIn):
""" """
sid,seq,data=stanza.getTagAttr('data','sid'),stanza.getTagAttr('data','seq'),stanza.getTagData('data') sid,seq,data=stanza.getTagAttr('data','sid'),stanza.getTagAttr('data','seq'),stanza.getTagData('data')
self.DEBUG('ReceiveHandler called sid->%s seq->%s'%(sid,seq),'info') self.DEBUG('ReceiveHandler called sid->%s seq->%s'%(sid,seq),'info')
try: seq=int(seq); data=base64.decodestring(data) try:
except: seq=''; data='' seq=int(seq)
data=base64.decodestring(data)
except Exception:
seq=''
data=''
err=None err=None
if not sid in self._streams.keys(): err=ERR_ITEM_NOT_FOUND if not sid in self._streams.keys(): err=ERR_ITEM_NOT_FOUND
else: else:

View File

@ -326,22 +326,30 @@ class Protocol(Node):
self.timestamp=None self.timestamp=None
for d in self.getTags('delay',namespace=NS_DELAY2): for d in self.getTags('delay',namespace=NS_DELAY2):
try: try:
if d.getAttr('stamp')<self.getTimestamp2(): self.setTimestamp(d.getAttr('stamp')) if d.getAttr('stamp') < self.getTimestamp2():
except: pass self.setTimestamp(d.getAttr('stamp'))
except Exception:
pass
if not self.timestamp: if not self.timestamp:
for x in self.getTags('x',namespace=NS_DELAY): for x in self.getTags('x',namespace=NS_DELAY):
try: try:
if x.getAttr('stamp')<self.getTimestamp(): self.setTimestamp(x.getAttr('stamp')) if x.getAttr('stamp') < self.getTimestamp():
except: pass self.setTimestamp(x.getAttr('stamp'))
except Exception:
pass
if timestamp is not None: self.setTimestamp(timestamp) # To auto-timestamp stanza just pass timestamp='' if timestamp is not None: self.setTimestamp(timestamp) # To auto-timestamp stanza just pass timestamp=''
def getTo(self): def getTo(self):
""" Return value of the 'to' attribute. """ """ Return value of the 'to' attribute. """
try: return self['to'] try:
except: return None return self['to']
except KeyError:
return None
def getFrom(self): def getFrom(self):
""" Return value of the 'from' attribute. """ """ Return value of the 'from' attribute. """
try: return self['from'] try:
except: return None return self['from']
except KeyError:
return None
def getTimestamp(self): def getTimestamp(self):
""" Return the timestamp in the 'yyyymmddThhmmss' format. """ """ Return the timestamp in the 'yyyymmddThhmmss' format. """
if self.timestamp: return self.timestamp if self.timestamp: return self.timestamp

View File

@ -127,8 +127,10 @@ class Session:
""" Reads all pending incoming data. """ Reads all pending incoming data.
Raises IOError on disconnection. Raises IOError on disconnection.
Blocks until at least one byte is read.""" Blocks until at least one byte is read."""
try: received = self._recv(10240) try:
except: received = '' received = self._recv(10240)
except socket.error:
received = ''
if len(received): # length of 0 means disconnect if len(received): # length of 0 means disconnect
self.DEBUG(repr(self.fileno())+' '+received,'got') self.DEBUG(repr(self.fileno())+' '+received,'got')

View File

@ -168,8 +168,7 @@ class Node(object):
return self.attrs return self.attrs
def getAttr(self, key): def getAttr(self, key):
""" Returns value of specified attribute. """ """ Returns value of specified attribute. """
try: return self.attrs[key] return self.attrs.get(key)
except: return None
def getChildren(self): def getChildren(self):
""" Returns all node's child nodes as list. """ """ Returns all node's child nodes as list. """
return self.kids return self.kids
@ -203,12 +202,16 @@ class Node(object):
return self.getTags(name, attrs, namespace, one=1) return self.getTags(name, attrs, namespace, one=1)
def getTagAttr(self,tag,attr): def getTagAttr(self,tag,attr):
""" Returns attribute value of the child with specified name (or None if no such attribute).""" """ Returns attribute value of the child with specified name (or None if no such attribute)."""
try: return self.getTag(tag).attrs[attr] try:
except: return None return self.getTag(tag).attrs[attr]
except:
return None
def getTagData(self,tag): def getTagData(self,tag):
""" Returns cocatenated CDATA of the child with specified name.""" """ Returns cocatenated CDATA of the child with specified name."""
try: return self.getTag(tag).getData() try:
except: return None return self.getTag(tag).getData()
except Exception:
return None
def getTags(self, name, attrs={}, namespace=None, one=0): def getTags(self, name, attrs={}, namespace=None, one=0):
""" Filters all child nodes using specified arguments as filter. """ Filters all child nodes using specified arguments as filter.
Returns the list of nodes found. """ Returns the list of nodes found. """
@ -264,13 +267,17 @@ class Node(object):
def setTagAttr(self,tag,attr,val): def setTagAttr(self,tag,attr,val):
""" Creates new node (if not already present) with name "tag" """ Creates new node (if not already present) with name "tag"
and sets it's attribute "attr" to value "val". """ and sets it's attribute "attr" to value "val". """
try: self.getTag(tag).attrs[attr]=val try:
except: self.addChild(tag,attrs={attr:val}) self.getTag(tag).attrs[attr]=val
except Exception:
self.addChild(tag,attrs={attr:val})
def setTagData(self,tag,val,attrs={}): def setTagData(self,tag,val,attrs={}):
""" Creates new node (if not already present) with name "tag" and (optionally) attributes "attrs" """ Creates new node (if not already present) with name "tag" and (optionally) attributes "attrs"
and sets it's CDATA to string "val". """ and sets it's CDATA to string "val". """
try: self.getTag(tag,attrs).setData(ustr(val)) try:
except: self.addChild(tag,attrs,payload=[ustr(val)]) self.getTag(tag,attrs).setData(ustr(val))
except Exception:
self.addChild(tag,attrs,payload=[ustr(val)])
def has_attr(self,key): def has_attr(self,key):
""" Checks if node have attribute "key".""" """ Checks if node have attribute "key"."""
return key in self.attrs return key in self.attrs

View File

@ -100,8 +100,10 @@ class TCPsocket(PlugIn):
self._recv=self._sock.recv self._recv=self._sock.recv
self.DEBUG("Successfully connected to remote host %s"%repr(server),'start') self.DEBUG("Successfully connected to remote host %s"%repr(server),'start')
return 'ok' return 'ok'
except: continue except Exception:
except: pass continue
except Exception:
pass
def plugout(self): def plugout(self):
""" Disconnect from the remote server and unregister self.disconnected method from """ Disconnect from the remote server and unregister self.disconnected method from
@ -112,12 +114,16 @@ class TCPsocket(PlugIn):
def receive(self): def receive(self):
""" Reads all pending incoming data. Calls owner's disconnected() method if appropriate.""" """ Reads all pending incoming data. Calls owner's disconnected() method if appropriate."""
try: received = self._recv(1024000) try:
except: received = '' received = self._recv(1024000)
except socket.error:
received = ''
while temp_failure_retry(select.select,[self._sock],[],[],0)[0]: while temp_failure_retry(select.select,[self._sock],[],[],0)[0]:
try: add = self._recv(1024000) try:
except: add='' add = self._recv(1024000)
except socket.error:
add=''
received +=add received +=add
if not add: break if not add: break

View File

@ -102,7 +102,8 @@ class SSLWrapper:
if self.exc_args[0] > 0: if self.exc_args[0] > 0:
errno = self.exc_args[0] errno = self.exc_args[0]
strerror = self.exc_args[1] strerror = self.exc_args[1]
except: pass except Exception:
pass
self.parent.__init__(self, errno, strerror) self.parent.__init__(self, errno, strerror)
@ -112,7 +113,8 @@ class SSLWrapper:
if len(ppeer) == 2 and isinstance(ppeer[0], basestring) \ if len(ppeer) == 2 and isinstance(ppeer[0], basestring) \
and isinstance(ppeer[1], int): and isinstance(ppeer[1], int):
self.peer = ppeer self.peer = ppeer
except: pass except Exception:
pass
def __str__(self): def __str__(self):
s = str(self.__class__) s = str(self.__class__)
@ -356,8 +358,10 @@ class NonBlockingTcp(PlugIn, IdleObject):
def pollend(self, retry=False): def pollend(self, retry=False):
if not self.printed_error: if not self.printed_error:
self.printed_error = True self.printed_error = True
try: self._do_receive(errors_only=True) try:
except: log.error("pollend: Got exception from _do_receive:", exc_info=True) self._do_receive(errors_only=True)
except Exception:
log.error("pollend: Got exception from _do_receive:", exc_info=True)
conn_failure_cb = self.on_connect_failure conn_failure_cb = self.on_connect_failure
self.disconnect() self.disconnect()
if conn_failure_cb: if conn_failure_cb:
@ -381,8 +385,10 @@ class NonBlockingTcp(PlugIn, IdleObject):
except socket.error, e: except socket.error, e:
if e[0] != errno.ENOTCONN: if e[0] != errno.ENOTCONN:
log.error("Error shutting down socket for %s:", self.getName(), exc_info=True) log.error("Error shutting down socket for %s:", self.getName(), exc_info=True)
try: sock.close() try:
except: log.error("Error closing socket for %s:", self.getName(), exc_info=True) sock.close()
except Exception:
log.error("Error closing socket for %s:", self.getName(), exc_info=True)
# socket descriptor cannot be (un)plugged anymore # socket descriptor cannot be (un)plugged anymore
self.fd = -1 self.fd = -1
if self.on_disconnect: if self.on_disconnect:

View File

@ -105,7 +105,7 @@ class ZeroconfListener(IdleObject):
self.started = False self.started = False
try: try:
self._serv.close() self._serv.close()
except: except socket.error:
pass pass
self.conn_holder.kill_all_connections() self.conn_holder.kill_all_connections()
@ -343,7 +343,7 @@ class P2PConnection(IdleObject, PlugIn):
self._sock = socket.socket(*ai[:3]) self._sock = socket.socket(*ai[:3])
self._sock.setblocking(False) self._sock.setblocking(False)
self._server = ai[4] self._server = ai[4]
except: except socket.error:
if sys.exc_value[0] != errno.EINPROGRESS: if sys.exc_value[0] != errno.EINPROGRESS:
# for all errors, we try other addresses # for all errors, we try other addresses
self.connect_to_next_ip() self.connect_to_next_ip()
@ -491,7 +491,7 @@ class P2PConnection(IdleObject, PlugIn):
try: try:
self._sock.shutdown(socket.SHUT_RDWR) self._sock.shutdown(socket.SHUT_RDWR)
self._sock.close() self._sock.close()
except: except socket.error:
# socket is already closed # socket is already closed
pass pass
self.fd = -1 self.fd = -1

View File

@ -640,7 +640,7 @@ class PreferencesWindow:
tv = gtk.TextView() tv = gtk.TextView()
try: try:
gtkspell.Spell(tv, lang) gtkspell.Spell(tv, lang)
except: except Exception:
dialogs.ErrorDialog( dialogs.ErrorDialog(
_('Dictionary for lang %s not available') % lang, _('Dictionary for lang %s not available') % lang,
_('You have to install %s dictionary to use spellchecking, or ' _('You have to install %s dictionary to use spellchecking, or '

View File

@ -795,7 +795,7 @@ default_name = ''):
# Save image # Save image
try: try:
pixbuf.save(file_path, type_) pixbuf.save(file_path, type_)
except: except Exception:
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
new_file_path = '.'.join(file_path.split('.')[:-1]) + '.jpeg' new_file_path = '.'.join(file_path.split('.')[:-1]) + '.jpeg'

View File

@ -1046,7 +1046,8 @@ if __name__ == '__main__':
change_cursor = tag change_cursor = tag
elif tag == tag_table.lookup('focus-out-line'): elif tag == tag_table.lookup('focus-out-line'):
over_line = True over_line = True
except: pass except Exception:
pass
#if line_tooltip.timeout != 0: #if line_tooltip.timeout != 0:
# Check if we should hide the line tooltip # Check if we should hide the line tooltip