diff --git a/django/contrib/flatpages/middleware.py b/django/contrib/flatpages/middleware.py index fb98c39a9e..955f856ea4 100644 --- a/django/contrib/flatpages/middleware.py +++ b/django/contrib/flatpages/middleware.py @@ -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 diff --git a/django/contrib/gis/db/backends/base.py b/django/contrib/gis/db/backends/base.py index ae2c920923..2d992cf36c 100644 --- a/django/contrib/gis/db/backends/base.py +++ b/django/contrib/gis/db/backends/base.py @@ -345,5 +345,5 @@ class SpatialRefSysMixin(object): """ try: return six.text_type(self.srs) - except: + except Exception: return six.text_type(self.wkt) diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py index b20b1b9157..093ec39bae 100644 --- a/django/contrib/gis/db/backends/spatialite/operations.py +++ b/django/contrib/gis/db/backends/spatialite/operations.py @@ -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 + cursor.execute('SELECT %s' % func) + row = cursor.fetchone() finally: cursor.close() return row[0] diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py index 55b887a445..5597a07e45 100644 --- a/django/contrib/gis/forms/fields.py +++ b/django/contrib/gis/forms/fields.py @@ -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 diff --git a/django/contrib/gis/geoip/__init__.py b/django/contrib/gis/geoip/__init__.py index c42dd2c72b..572c778e81 100644 --- a/django/contrib/gis/geoip/__init__.py +++ b/django/contrib/gis/geoip/__init__.py @@ -14,5 +14,5 @@ try: from .base import GeoIP, GeoIPException HAS_GEOIP = True -except: +except ImportError: HAS_GEOIP = False diff --git a/django/contrib/gis/geos/libgeos.py b/django/contrib/gis/geos/libgeos.py index 6963b786c8..c3f30b3f14 100644 --- a/django/contrib/gis/geos/libgeos.py +++ b/django/contrib/gis/geos/libgeos.py @@ -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) diff --git a/django/contrib/gis/sitemaps/views.py b/django/contrib/gis/sitemaps/views.py index 9682c125d2..d64691e971 100644 --- a/django/contrib/gis/sitemaps/views.py +++ b/django/contrib/gis/sitemaps/views.py @@ -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] diff --git a/django/contrib/gis/utils/__init__.py b/django/contrib/gis/utils/__init__.py index c6617d299f..bdec5f0742 100644 --- a/django/contrib/gis/utils/__init__.py +++ b/django/contrib/gis/utils/__init__.py @@ -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 diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index 9c696c78b3..8b7b451e51 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -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: diff --git a/django/core/mail/backends/console.py b/django/core/mail/backends/console.py index 389e06b37f..1ec3d3afdc 100644 --- a/django/core/mail/backends/console.py +++ b/django/core/mail/backends/console.py @@ -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 diff --git a/django/core/mail/backends/smtp.py b/django/core/mail/backends/smtp.py index c7f4a1a801..49145e1abc 100644 --- a/django/core/mail/backends/smtp.py +++ b/django/core/mail/backends/smtp.py @@ -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 diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index 7a7a7bb09d..eac95e6b37 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -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: diff --git a/django/core/management/sql.py b/django/core/management/sql.py index f5e0b7367b..14f5d6b6b0 100644 --- a/django/core/management/sql.py +++ b/django/core/management/sql.py @@ -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 diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index 9a99a07ee1..a94d95e1ea 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -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 diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 9a5193e49b..af0222b423 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -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': diff --git a/django/http/request.py b/django/http/request.py index 9f9f32b1b4..f19ccaf068 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -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() diff --git a/django/template/loader_tags.py b/django/template/loader_tags.py index 570366ea72..28b948174f 100644 --- a/django/template/loader_tags.py +++ b/django/template/loader_tags.py @@ -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 ''