Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Baptiste Mispelon authored
2  django/contrib/flatpages/middleware.py
@@ -12,7 +12,7 @@ def process_response(self, request, response):
12 12
         # is a middleware, we can't assume the errors will be caught elsewhere.
13 13
         except Http404:
14 14
             return response
15  
-        except:
  15
+        except Exception:
16 16
             if settings.DEBUG:
17 17
                 raise
18 18
             return response
2  django/contrib/gis/db/backends/base.py
@@ -345,5 +345,5 @@ def __str__(self):
345 345
         """
346 346
         try:
347 347
             return six.text_type(self.srs)
348  
-        except:
  348
+        except Exception:
349 349
             return six.text_type(self.wkt)
9  django/contrib/gis/db/backends/spatialite/operations.py
@@ -238,15 +238,12 @@ def _get_spatialite_func(self, func):
238 238
         """
239 239
         Helper routine for calling SpatiaLite functions and returning
240 240
         their result.
  241
+        Any error occuring in this method should be handled by the caller.
241 242
         """
242 243
         cursor = self.connection._cursor()
243 244
         try:
244  
-            try:
245  
-                cursor.execute('SELECT %s' % func)
246  
-                row = cursor.fetchone()
247  
-            except:
248  
-                # Responsibility of caller to perform error handling.
249  
-                raise
  245
+            cursor.execute('SELECT %s' % func)
  246
+            row = cursor.fetchone()
250 247
         finally:
251 248
             cursor.close()
252 249
         return row[0]
2  django/contrib/gis/forms/fields.py
@@ -73,7 +73,7 @@ def clean(self, value):
73 73
             elif self.srid != -1 and self.srid != geom.srid:
74 74
                 try:
75 75
                     geom.transform(self.srid)
76  
-                except:
  76
+                except GEOSException:
77 77
                     raise forms.ValidationError(self.error_messages['transform_error'], code='transform_error')
78 78
 
79 79
         return geom
2  django/contrib/gis/geoip/__init__.py
@@ -14,5 +14,5 @@
14 14
 try:
15 15
     from .base import GeoIP, GeoIPException
16 16
     HAS_GEOIP = True
17  
-except:
  17
+except ImportError:
18 18
     HAS_GEOIP = False
4  django/contrib/gis/geos/libgeos.py
@@ -65,7 +65,7 @@ def notice_h(fmt, lst):
65 65
     fmt, lst = fmt.decode(), lst.decode()
66 66
     try:
67 67
         warn_msg = fmt % lst
68  
-    except:
  68
+    except TypeError:
69 69
         warn_msg = fmt
70 70
     logger.warning('GEOS_NOTICE: %s\n' % warn_msg)
71 71
 notice_h = NOTICEFUNC(notice_h)
@@ -75,7 +75,7 @@ def error_h(fmt, lst):
75 75
     fmt, lst = fmt.decode(), lst.decode()
76 76
     try:
77 77
         err_msg = fmt % lst
78  
-    except:
  78
+    except TypeError:
79 79
         err_msg = fmt
80 80
     logger.error('GEOS_ERROR: %s\n' % err_msg)
81 81
 error_h = ERRORFUNC(error_h)
9  django/contrib/gis/sitemaps/views.py
@@ -8,6 +8,7 @@
8 8
 from django.contrib.gis.db.models.fields import GeometryField
9 9
 from django.db import connections, DEFAULT_DB_ALIAS
10 10
 from django.db.models import get_model
  11
+from django.db.models.fields import FieldDoesNotExist
11 12
 from django.utils import six
12 13
 from django.utils.translation import ugettext as _
13 14
 
@@ -77,10 +78,10 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB
77 78
 
78 79
     if field_name:
79 80
         try:
80  
-            info = klass._meta.get_field_by_name(field_name)
81  
-            if not isinstance(info[0], GeometryField):
82  
-                raise Exception
83  
-        except:
  81
+            field, _, _, _ = klass._meta.get_field_by_name(field_name)
  82
+            if not isinstance(field, GeometryField):
  83
+                raise FieldDoesNotExist
  84
+        except FieldDoesNotExist:
84 85
             raise Http404('Invalid geometry field.')
85 86
 
86 87
     connection = connections[using]
3  django/contrib/gis/utils/__init__.py
@@ -7,11 +7,12 @@
7 7
     from django.contrib.gis.utils.ogrinfo import ogrinfo, sample
8 8
     from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect
9 9
     from django.contrib.gis.utils.srs import add_postgis_srs, add_srs_entry
  10
+    from django.core.exceptions import ImproperlyConfigured
10 11
     try:
11 12
         # LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
12 13
         # so this needs to be in try/except.
13 14
         from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError
14  
-    except:
  15
+    except ImproperlyConfigured:
15 16
         pass
16 17
 
17 18
 from django.contrib.gis.utils.wkt import precision_wkt
10  django/contrib/gis/utils/layermapping.py
@@ -7,7 +7,7 @@
7 7
    http://geodjango.org/docs/layermapping.html
8 8
 """
9 9
 import sys
10  
-from decimal import Decimal
  10
+from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
11 11
 from django.core.exceptions import ObjectDoesNotExist
12 12
 from django.db import connections, router
13 13
 from django.contrib.gis.db.models import GeometryField
@@ -337,7 +337,7 @@ def verify_ogr_field(self, ogr_field, model_field):
337 337
             try:
338 338
                 # Creating an instance of the Decimal value to use.
339 339
                 d = Decimal(str(ogr_field.value))
340  
-            except:
  340
+            except DecimalInvalidOperation:
341 341
                 raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)
342 342
 
343 343
             # Getting the decimal value as a tuple.
@@ -365,7 +365,7 @@ def verify_ogr_field(self, ogr_field, model_field):
365 365
             # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
366 366
             try:
367 367
                 val = int(ogr_field.value)
368  
-            except:
  368
+            except ValueError:
369 369
                 raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
370 370
         else:
371 371
             val = ogr_field.value
@@ -547,8 +547,6 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
547 547
                         m.save(using=self.using)
548 548
                         num_saved += 1
549 549
                         if verbose: stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m))
550  
-                    except SystemExit:
551  
-                        raise
552 550
                     except Exception as msg:
553 551
                         if strict:
554 552
                             # Bailing out if the `strict` keyword is set.
@@ -588,7 +586,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0):
588 586
                 try:
589 587
                     num_feat, num_saved = _save(step_slice, num_feat, num_saved)
590 588
                     beg = end
591  
-                except:
  589
+                except:  # Deliberately catch everything
592 590
                     stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice))
593 591
                     raise
594 592
         else:
2  django/core/mail/backends/console.py
@@ -28,7 +28,7 @@ def send_messages(self, email_messages):
28 28
                     msg_count += 1
29 29
                 if stream_created:
30 30
                     self.close()
31  
-            except:
  31
+            except Exception:
32 32
                 if not self.fail_silently:
33 33
                     raise
34 34
         return msg_count
6  django/core/mail/backends/smtp.py
@@ -56,7 +56,7 @@ def open(self):
56 56
             if self.username and self.password:
57 57
                 self.connection.login(self.username, self.password)
58 58
             return True
59  
-        except:
  59
+        except smtplib.SMTPException:
60 60
             if not self.fail_silently:
61 61
                 raise
62 62
 
@@ -72,7 +72,7 @@ def close(self):
72 72
                 # sometimes, or when the connection was already disconnected
73 73
                 # by the server.
74 74
                 self.connection.close()
75  
-            except:
  75
+            except smtplib.SMTPException:
76 76
                 if self.fail_silently:
77 77
                     return
78 78
                 raise
@@ -113,7 +113,7 @@ def _send(self, email_message):
113 113
         try:
114 114
             self.connection.sendmail(from_email, recipients,
115 115
                     force_bytes(message.as_string(), charset))
116  
-        except:
  116
+        except smtplib.SMTPException:
117 117
             if not self.fail_silently:
118 118
                 raise
119 119
             return False
4  django/core/management/__init__.py
@@ -209,7 +209,7 @@ def _process_args(self, largs, rargs, values):
209 209
                     # dealing with options
210 210
                     del rargs[0]
211 211
                     raise Exception
212  
-            except:
  212
+            except:  # Needed because we might need to catch a SystemExit
213 213
                 largs.append(arg)
214 214
 
215 215
 class ManagementUtility(object):
@@ -360,7 +360,7 @@ def execute(self):
360 360
         try:
361 361
             options, args = parser.parse_args(self.argv)
362 362
             handle_default_options(options)
363  
-        except:
  363
+        except:  # Needed because parser.parse_args can raise SystemExit
364 364
             pass # Ignore any option errors at this point.
365 365
 
366 366
         try:
2  django/core/management/sql.py
@@ -63,7 +63,7 @@ def sql_delete(app, style, connection):
63 63
     # This should work even if a connection isn't available
64 64
     try:
65 65
         cursor = connection.cursor()
66  
-    except:
  66
+    except Exception:
67 67
         cursor = None
68 68
 
69 69
     # Figure out which tables already exist
2  django/db/backends/oracle/base.py
@@ -620,7 +620,7 @@ def init_connection_state(self):
620 620
 
621 621
         try:
622 622
             self.connection.stmtcachesize = 20
623  
-        except:
  623
+        except AttributeError:
624 624
             # Django docs specify cx_Oracle version 4.3.1 or higher, but
625 625
             # stmtcachesize is available only in 4.3.2 and up.
626 626
             pass
11  django/http/multipartparser.py
@@ -7,6 +7,7 @@
7 7
 from __future__ import unicode_literals
8 8
 
9 9
 import base64
  10
+import binascii
10 11
 import cgi
11 12
 import sys
12 13
 
@@ -33,6 +34,8 @@ class InputStreamExhausted(Exception):
33 34
 FILE = "file"
34 35
 FIELD = "field"
35 36
 
  37
+_BASE64_DECODE_ERROR = TypeError if six.PY2 else binascii.Error
  38
+
36 39
 class MultiPartParser(object):
37 40
     """
38 41
     A rfc2388 multipart/form-data parser.
@@ -161,8 +164,8 @@ def parse(self):
161 164
                     if transfer_encoding == 'base64':
162 165
                         raw_data = field_stream.read()
163 166
                         try:
164  
-                            data = str(raw_data).decode('base64')
165  
-                        except:
  167
+                            data = base64.b64decode(raw_data)
  168
+                        except _BASE64_DECODE_ERROR:
166 169
                             data = raw_data
167 170
                     else:
168 171
                         data = field_stream.read()
@@ -546,7 +549,7 @@ def _parse_header(line):
546 549
         main_value_pair, params = parse_header(line)
547 550
         try:
548 551
             name, value = main_value_pair.split(':', 1)
549  
-        except:
  552
+        except ValueError:
550 553
             raise ValueError("Invalid header: %r" % line)
551 554
         return name, (value, params)
552 555
 
@@ -571,7 +574,7 @@ def _parse_header(line):
571 574
         # parameters") is from the Python docs.
572 575
         try:
573 576
             name, (value, params) = _parse_header(line)
574  
-        except:
  577
+        except ValueError:
575 578
             continue
576 579
 
577 580
         if name == 'content-disposition':
6  django/http/request.py
@@ -16,7 +16,7 @@
16 16
 from django.core import signing
17 17
 from django.core.exceptions import DisallowedHost, ImproperlyConfigured
18 18
 from django.core.files import uploadhandler
19  
-from django.http.multipartparser import MultiPartParser
  19
+from django.http.multipartparser import MultiPartParser, MultiPartParserError
20 20
 from django.utils import six
21 21
 from django.utils.datastructures import MultiValueDict, ImmutableList
22 22
 from django.utils.encoding import force_bytes, force_text, force_str, iri_to_uri
@@ -222,7 +222,7 @@ def _load_post_and_files(self):
222 222
                 data = self
223 223
             try:
224 224
                 self._post, self._files = self.parse_file_upload(self.META, data)
225  
-            except:
  225
+            except MultiPartParserError:
226 226
                 # An error occured while parsing POST data. Since when
227 227
                 # formatting the error the request handler might access
228 228
                 # self.POST, set self._post and self._file to prevent
@@ -230,7 +230,7 @@ def _load_post_and_files(self):
230 230
                 # Mark that an error occured. This allows self.__repr__ to
231 231
                 # be explicit about it instead of simply representing an
232 232
                 # empty POST
233  
-                self._mark_post_parse_error()
  233
+                # self._mark_post_parse_error()
234 234
                 raise
235 235
         elif self.META.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'):
236 236
             self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
2  django/template/loader_tags.py
@@ -143,7 +143,7 @@ def render(self, context):
143 143
                 return template.render(context.new(values))
144 144
             with context.push(**values):
145 145
                 return template.render(context)
146  
-        except:
  146
+        except Exception:
147 147
             if settings.TEMPLATE_DEBUG:
148 148
                 raise
149 149
             return ''

0 notes on commit 20472aa

Tom Christie

This has erroneously made it's way in.

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

Please sign in to comment.
Something went wrong with that request. Please try again.