Fixed #21189: Cleaned up usage of bare except clauses.

Thanks to berkerpeksag for the report and to claudep
for the review.
This commit is contained in:
Baptiste Mispelon 2013-09-30 17:55:14 +02:00
parent 948d209ada
commit 20472aa827
17 changed files with 39 additions and 39 deletions

View File

@ -12,7 +12,7 @@ class FlatpageFallbackMiddleware(object):
# is a middleware, we can't assume the errors will be caught elsewhere.
except Http404:
return response
except:
except Exception:
if settings.DEBUG:
raise
return response

View File

@ -345,5 +345,5 @@ class SpatialRefSysMixin(object):
"""
try:
return six.text_type(self.srs)
except:
except Exception:
return six.text_type(self.wkt)

View File

@ -238,15 +238,12 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
"""
Helper routine for calling SpatiaLite functions and returning
their result.
Any error occuring in this method should be handled by the caller.
"""
cursor = self.connection._cursor()
try:
try:
cursor.execute('SELECT %s' % func)
row = cursor.fetchone()
except:
# Responsibility of caller to perform error handling.
raise
finally:
cursor.close()
return row[0]

View File

@ -73,7 +73,7 @@ class GeometryField(forms.Field):
elif self.srid != -1 and self.srid != geom.srid:
try:
geom.transform(self.srid)
except:
except GEOSException:
raise forms.ValidationError(self.error_messages['transform_error'], code='transform_error')
return geom

View File

@ -14,5 +14,5 @@
try:
from .base import GeoIP, GeoIPException
HAS_GEOIP = True
except:
except ImportError:
HAS_GEOIP = False

View File

@ -65,7 +65,7 @@ def notice_h(fmt, lst):
fmt, lst = fmt.decode(), lst.decode()
try:
warn_msg = fmt % lst
except:
except TypeError:
warn_msg = fmt
logger.warning('GEOS_NOTICE: %s\n' % warn_msg)
notice_h = NOTICEFUNC(notice_h)
@ -75,7 +75,7 @@ def error_h(fmt, lst):
fmt, lst = fmt.decode(), lst.decode()
try:
err_msg = fmt % lst
except:
except TypeError:
err_msg = fmt
logger.error('GEOS_ERROR: %s\n' % err_msg)
error_h = ERRORFUNC(error_h)

View File

@ -8,6 +8,7 @@ from django.core.paginator import EmptyPage, PageNotAnInteger
from django.contrib.gis.db.models.fields import GeometryField
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.models import get_model
from django.db.models.fields import FieldDoesNotExist
from django.utils import six
from django.utils.translation import ugettext as _
@ -77,10 +78,10 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB
if field_name:
try:
info = klass._meta.get_field_by_name(field_name)
if not isinstance(info[0], GeometryField):
raise Exception
except:
field, _, _, _ = klass._meta.get_field_by_name(field_name)
if not isinstance(field, GeometryField):
raise FieldDoesNotExist
except FieldDoesNotExist:
raise Http404('Invalid geometry field.')
connection = connections[using]

View File

@ -7,11 +7,12 @@ if HAS_GDAL:
from django.contrib.gis.utils.ogrinfo import ogrinfo, sample
from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect
from django.contrib.gis.utils.srs import add_postgis_srs, add_srs_entry
from django.core.exceptions import ImproperlyConfigured
try:
# LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
# so this needs to be in try/except.
from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError
except:
except ImproperlyConfigured:
pass
from django.contrib.gis.utils.wkt import precision_wkt

View File

@ -7,7 +7,7 @@
http://geodjango.org/docs/layermapping.html
"""
import sys
from decimal import Decimal
from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
from django.core.exceptions import ObjectDoesNotExist
from django.db import connections, router
from django.contrib.gis.db.models import GeometryField
@ -337,7 +337,7 @@ class LayerMapping(object):
try:
# Creating an instance of the Decimal value to use.
d = Decimal(str(ogr_field.value))
except:
except DecimalInvalidOperation:
raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)
# Getting the decimal value as a tuple.
@ -365,7 +365,7 @@ class LayerMapping(object):
# Attempt to convert any OFTReal and OFTString value to an OFTInteger.
try:
val = int(ogr_field.value)
except:
except ValueError:
raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
else:
val = ogr_field.value
@ -547,8 +547,6 @@ class LayerMapping(object):
m.save(using=self.using)
num_saved += 1
if verbose: stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m))
except SystemExit:
raise
except Exception as msg:
if strict:
# Bailing out if the `strict` keyword is set.
@ -588,7 +586,7 @@ class LayerMapping(object):
try:
num_feat, num_saved = _save(step_slice, num_feat, num_saved)
beg = end
except:
except: # Deliberately catch everything
stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice))
raise
else:

View File

@ -28,7 +28,7 @@ class EmailBackend(BaseEmailBackend):
msg_count += 1
if stream_created:
self.close()
except:
except Exception:
if not self.fail_silently:
raise
return msg_count

View File

@ -56,7 +56,7 @@ class EmailBackend(BaseEmailBackend):
if self.username and self.password:
self.connection.login(self.username, self.password)
return True
except:
except smtplib.SMTPException:
if not self.fail_silently:
raise
@ -72,7 +72,7 @@ class EmailBackend(BaseEmailBackend):
# sometimes, or when the connection was already disconnected
# by the server.
self.connection.close()
except:
except smtplib.SMTPException:
if self.fail_silently:
return
raise
@ -113,7 +113,7 @@ class EmailBackend(BaseEmailBackend):
try:
self.connection.sendmail(from_email, recipients,
force_bytes(message.as_string(), charset))
except:
except smtplib.SMTPException:
if not self.fail_silently:
raise
return False

View File

@ -209,7 +209,7 @@ class LaxOptionParser(OptionParser):
# dealing with options
del rargs[0]
raise Exception
except:
except: # Needed because we might need to catch a SystemExit
largs.append(arg)
class ManagementUtility(object):
@ -360,7 +360,7 @@ class ManagementUtility(object):
try:
options, args = parser.parse_args(self.argv)
handle_default_options(options)
except:
except: # Needed because parser.parse_args can raise SystemExit
pass # Ignore any option errors at this point.
try:

View File

@ -63,7 +63,7 @@ def sql_delete(app, style, connection):
# This should work even if a connection isn't available
try:
cursor = connection.cursor()
except:
except Exception:
cursor = None
# Figure out which tables already exist

View File

@ -620,7 +620,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
try:
self.connection.stmtcachesize = 20
except:
except AttributeError:
# Django docs specify cx_Oracle version 4.3.1 or higher, but
# stmtcachesize is available only in 4.3.2 and up.
pass

View File

@ -7,6 +7,7 @@ file upload handlers for processing.
from __future__ import unicode_literals
import base64
import binascii
import cgi
import sys
@ -33,6 +34,8 @@ RAW = "raw"
FILE = "file"
FIELD = "field"
_BASE64_DECODE_ERROR = TypeError if six.PY2 else binascii.Error
class MultiPartParser(object):
"""
A rfc2388 multipart/form-data parser.
@ -161,8 +164,8 @@ class MultiPartParser(object):
if transfer_encoding == 'base64':
raw_data = field_stream.read()
try:
data = str(raw_data).decode('base64')
except:
data = base64.b64decode(raw_data)
except _BASE64_DECODE_ERROR:
data = raw_data
else:
data = field_stream.read()
@ -546,7 +549,7 @@ def parse_boundary_stream(stream, max_header_size):
main_value_pair, params = parse_header(line)
try:
name, value = main_value_pair.split(':', 1)
except:
except ValueError:
raise ValueError("Invalid header: %r" % line)
return name, (value, params)
@ -571,7 +574,7 @@ def parse_boundary_stream(stream, max_header_size):
# parameters") is from the Python docs.
try:
name, (value, params) = _parse_header(line)
except:
except ValueError:
continue
if name == 'content-disposition':

View File

@ -16,7 +16,7 @@ from django.conf import settings
from django.core import signing
from django.core.exceptions import DisallowedHost, ImproperlyConfigured
from django.core.files import uploadhandler
from django.http.multipartparser import MultiPartParser
from django.http.multipartparser import MultiPartParser, MultiPartParserError
from django.utils import six
from django.utils.datastructures import MultiValueDict, ImmutableList
from django.utils.encoding import force_bytes, force_text, force_str, iri_to_uri
@ -222,7 +222,7 @@ class HttpRequest(object):
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except:
except MultiPartParserError:
# An error occured while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
@ -230,7 +230,7 @@ class HttpRequest(object):
# Mark that an error occured. This allows self.__repr__ to
# be explicit about it instead of simply representing an
# empty POST
self._mark_post_parse_error()
# self._mark_post_parse_error()
raise
elif self.META.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'):
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()

View File

@ -143,7 +143,7 @@ class IncludeNode(Node):
return template.render(context.new(values))
with context.push(**values):
return template.render(context)
except:
except Exception:
if settings.TEMPLATE_DEBUG:
raise
return ''