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. # is a middleware, we can't assume the errors will be caught elsewhere.
except Http404: except Http404:
return response return response
except: except Exception:
if settings.DEBUG: if settings.DEBUG:
raise raise
return response return response

View File

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

View File

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

View File

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

View File

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

View File

@ -65,7 +65,7 @@ def notice_h(fmt, lst):
fmt, lst = fmt.decode(), lst.decode() fmt, lst = fmt.decode(), lst.decode()
try: try:
warn_msg = fmt % lst warn_msg = fmt % lst
except: except TypeError:
warn_msg = fmt warn_msg = fmt
logger.warning('GEOS_NOTICE: %s\n' % warn_msg) logger.warning('GEOS_NOTICE: %s\n' % warn_msg)
notice_h = NOTICEFUNC(notice_h) notice_h = NOTICEFUNC(notice_h)
@ -75,7 +75,7 @@ def error_h(fmt, lst):
fmt, lst = fmt.decode(), lst.decode() fmt, lst = fmt.decode(), lst.decode()
try: try:
err_msg = fmt % lst err_msg = fmt % lst
except: except TypeError:
err_msg = fmt err_msg = fmt
logger.error('GEOS_ERROR: %s\n' % err_msg) logger.error('GEOS_ERROR: %s\n' % err_msg)
error_h = ERRORFUNC(error_h) 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.contrib.gis.db.models.fields import GeometryField
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
from django.db.models import get_model from django.db.models import get_model
from django.db.models.fields import FieldDoesNotExist
from django.utils import six from django.utils import six
from django.utils.translation import ugettext as _ 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: if field_name:
try: try:
info = klass._meta.get_field_by_name(field_name) field, _, _, _ = klass._meta.get_field_by_name(field_name)
if not isinstance(info[0], GeometryField): if not isinstance(field, GeometryField):
raise Exception raise FieldDoesNotExist
except: except FieldDoesNotExist:
raise Http404('Invalid geometry field.') raise Http404('Invalid geometry field.')
connection = connections[using] 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.ogrinfo import ogrinfo, sample
from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect
from django.contrib.gis.utils.srs import add_postgis_srs, add_srs_entry from django.contrib.gis.utils.srs import add_postgis_srs, add_srs_entry
from django.core.exceptions import ImproperlyConfigured
try: try:
# LayerMapping requires DJANGO_SETTINGS_MODULE to be set, # LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
# so this needs to be in try/except. # so this needs to be in try/except.
from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError
except: except ImproperlyConfigured:
pass pass
from django.contrib.gis.utils.wkt import precision_wkt from django.contrib.gis.utils.wkt import precision_wkt

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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