Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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

Thanks to berkerpeksag for the report and to claudep
for the review.
  • Loading branch information...
commit 20472aa827669d2b83b74e521504e88e18d086a1 1 parent 948d209
@bmispelon bmispelon authored
View
2  django/contrib/flatpages/middleware.py
@@ -12,7 +12,7 @@ def process_response(self, request, response):
# 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
2  django/contrib/gis/db/backends/base.py
@@ -345,5 +345,5 @@ def __str__(self):
"""
try:
return six.text_type(self.srs)
- except:
+ except Exception:
return six.text_type(self.wkt)
View
9 django/contrib/gis/db/backends/spatialite/operations.py
@@ -238,15 +238,12 @@ def _get_spatialite_func(self, func):
"""
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]
View
2  django/contrib/gis/forms/fields.py
@@ -73,7 +73,7 @@ def clean(self, value):
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
2  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
View
4 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)
View
9 django/contrib/gis/sitemaps/views.py
@@ -8,6 +8,7 @@
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
3  django/contrib/gis/utils/__init__.py
@@ -7,11 +7,12 @@
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
10 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 @@ def verify_ogr_field(self, ogr_field, model_field):
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 @@ def verify_ogr_field(self, ogr_field, model_field):
# 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 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
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 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
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
2  django/core/mail/backends/console.py
@@ -28,7 +28,7 @@ def send_messages(self, email_messages):
msg_count += 1
if stream_created:
self.close()
- except:
+ except Exception:
if not self.fail_silently:
raise
return msg_count
View
6 django/core/mail/backends/smtp.py
@@ -56,7 +56,7 @@ def open(self):
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 @@ def close(self):
# 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 @@ def _send(self, email_message):
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
4 django/core/management/__init__.py
@@ -209,7 +209,7 @@ def _process_args(self, largs, rargs, values):
# 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 @@ def execute(self):
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
2  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
View
2  django/db/backends/oracle/base.py
@@ -620,7 +620,7 @@ def init_connection_state(self):
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
11 django/http/multipartparser.py
@@ -7,6 +7,7 @@
from __future__ import unicode_literals
import base64
+import binascii
import cgi
import sys
@@ -33,6 +34,8 @@ class InputStreamExhausted(Exception):
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 @@ def parse(self):
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_header(line):
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_header(line):
# parameters") is from the Python docs.
try:
name, (value, params) = _parse_header(line)
- except:
+ except ValueError:
continue
if name == 'content-disposition':
View
6 django/http/request.py
@@ -16,7 +16,7 @@
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 @@ def _load_post_and_files(self):
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 @@ def _load_post_and_files(self):
# 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()

This has erroneously made it's way in.

Ticket and attached pull request here: https://code.djangoproject.com/ticket/21447

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
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
2  django/template/loader_tags.py
@@ -143,7 +143,7 @@ def render(self, context):
return template.render(context.new(values))
with context.push(**values):
return template.render(context)
- except:
+ except Exception:
if settings.TEMPLATE_DEBUG:
raise
return ''
Please sign in to comment.
Something went wrong with that request. Please try again.