Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Removed many uses of bare "except:", which were either going to a) si…

…lence real issues, or b) were impossible to hit.
  • Loading branch information...
commit 335a9f9cf1e2f40679e91cf42cfd0e636885a397 1 parent 257c401
authored
10  django/contrib/localflavor/hr/forms.py
@@ -4,6 +4,7 @@
4 4
 """
5 5
 from __future__ import absolute_import, unicode_literals
6 6
 
  7
+import datetime
7 8
 import re
8 9
 
9 10
 from django.contrib.localflavor.hr.hr_choices import (
@@ -91,17 +92,16 @@ def clean(self, value):
91 92
         dd = int(matches.group('dd'))
92 93
         mm = int(matches.group('mm'))
93 94
         yyy = int(matches.group('yyy'))
94  
-        import datetime
95 95
         try:
96  
-            datetime.date(yyy,mm,dd)
97  
-        except:
  96
+            datetime.date(yyy, mm, dd)
  97
+        except ValueError:
98 98
             raise ValidationError(self.error_messages['date'])
99 99
 
100 100
         # Validate checksum.
101 101
         k = matches.group('k')
102 102
         checksum = 0
103  
-        for i,j in zip(range(7,1,-1),range(6)):
104  
-            checksum+=i*(int(value[j])+int(value[13-i]))
  103
+        for i, j in zip(range(7, 1, -1), range(6)):
  104
+            checksum += i * (int(value[j]) + int(value[13 - i]))
105 105
         m = 11 - checksum % 11
106 106
         if m == 10:
107 107
             raise ValidationError(self.error_messages['invalid'])
22  django/contrib/localflavor/ro/forms.py
@@ -4,6 +4,8 @@
4 4
 """
5 5
 from __future__ import absolute_import, unicode_literals
6 6
 
  7
+import datetime
  8
+
7 9
 from django.contrib.localflavor.ro.ro_counties import COUNTIES_CHOICES
8 10
 from django.core.validators import EMPTY_VALUES
9 11
 from django.forms import ValidationError, Field, RegexField, Select
@@ -69,10 +71,9 @@ def clean(self, value):
69 71
         if value in EMPTY_VALUES:
70 72
             return ''
71 73
         # check birthdate digits
72  
-        import datetime
73 74
         try:
74  
-            datetime.date(int(value[1:3]),int(value[3:5]),int(value[5:7]))
75  
-        except:
  75
+            datetime.date(int(value[1:3]), int(value[3:5]), int(value[5:7]))
  76
+        except ValueError:
76 77
             raise ValidationError(self.error_messages['invalid'])
77 78
         # checksum
78 79
         key = '279146358279'
@@ -118,7 +119,7 @@ def clean(self, value):
118 119
         # search for county name
119 120
         normalized_CC = []
120 121
         for entry in COUNTIES_CHOICES:
121  
-            normalized_CC.append((entry[0],entry[1].upper()))
  122
+            normalized_CC.append((entry[0], entry[1].upper()))
122 123
         for entry in normalized_CC:
123 124
             if entry[1] == value:
124 125
                 return entry[0]
@@ -153,8 +154,8 @@ def clean(self, value):
153 154
         value = super(ROIBANField, self).clean(value)
154 155
         if value in EMPTY_VALUES:
155 156
             return ''
156  
-        value = value.replace('-','')
157  
-        value = value.replace(' ','')
  157
+        value = value.replace('-', '')
  158
+        value = value.replace(' ', '')
158 159
         value = value.upper()
159 160
         if value[0:2] != 'RO':
160 161
             raise ValidationError(self.error_messages['invalid'])
@@ -185,10 +186,10 @@ def clean(self, value):
185 186
         value = super(ROPhoneNumberField, self).clean(value)
186 187
         if value in EMPTY_VALUES:
187 188
             return ''
188  
-        value = value.replace('-','')
189  
-        value = value.replace('(','')
190  
-        value = value.replace(')','')
191  
-        value = value.replace(' ','')
  189
+        value = value.replace('-', '')
  190
+        value = value.replace('(', '')
  191
+        value = value.replace(')', '')
  192
+        value = value.replace(' ', '')
192 193
         if len(value) != 10:
193 194
             raise ValidationError(self.error_messages['invalid'])
194 195
         return value
@@ -202,4 +203,3 @@ class ROPostalCodeField(RegexField):
202 203
     def __init__(self, max_length=6, min_length=6, *args, **kwargs):
203 204
         super(ROPostalCodeField, self).__init__(r'^[0-9][0-8][0-9]{4}$',
204 205
                 max_length, min_length, *args, **kwargs)
205  
-
2  django/core/cache/backends/memcached.py
@@ -141,7 +141,7 @@ def __init__(self, server, params):
141 141
         )
142 142
         try:
143 143
             import memcache
144  
-        except:
  144
+        except ImportError:
145 145
             raise InvalidCacheBackendError(
146 146
                 "Memcached cache backend requires either the 'memcache' or 'cmemcache' library"
147 147
                 )
2  django/core/mail/backends/console.py
@@ -21,7 +21,7 @@ def send_messages(self, email_messages):
21 21
                 stream_created = self.open()
22 22
                 for message in email_messages:
23 23
                     self.stream.write('%s\n' % message.message().as_string())
24  
-                    self.stream.write('-'*79)
  24
+                    self.stream.write('-' * 79)
25 25
                     self.stream.write('\n')
26 26
                     self.stream.flush()  # flush after each message
27 27
                 if stream_created:
5  django/db/backends/sqlite3/base.py
@@ -412,7 +412,4 @@ def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
412 412
     return str(dt)
413 413
 
414 414
 def _sqlite_regexp(re_pattern, re_string):
415  
-    try:
416  
-        return bool(re.search(re_pattern, re_string))
417  
-    except:
418  
-        return False
  415
+    return bool(re.search(re_pattern, re_string))
5  django/http/multipartparser.py
@@ -68,11 +68,10 @@ def __init__(self, META, input_data, upload_handlers, encoding=None):
68 68
         if not boundary or not cgi.valid_boundary(boundary):
69 69
             raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)
70 70
 
71  
-
72 71
         # Content-Length should contain the length of the body we are about
73 72
         # to receive.
74 73
         try:
75  
-            content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH',0)))
  74
+            content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH', 0)))
76 75
         except (ValueError, TypeError):
77 76
             content_length = 0
78 77
 
@@ -178,7 +177,7 @@ def parse(self):
178 177
 
179 178
                     content_type = meta_data.get('content-type', ('',))[0].strip()
180 179
                     try:
181  
-                        charset = meta_data.get('content-type', (0,{}))[1].get('charset', None)
  180
+                        charset = meta_data.get('content-type', (0, {}))[1].get('charset', None)
182 181
                     except:
183 182
                         charset = None
184 183
 
2  tests/regressiontests/file_uploads/tests.py
@@ -100,7 +100,7 @@ def test_unicode_file_name(self):
100 100
 
101 101
         try:
102 102
             os.unlink(file1.name)
103  
-        except:
  103
+        except OSError:
104 104
             pass
105 105
 
106 106
         self.assertEqual(response.status_code, 200)
4  tests/regressiontests/handlers/tests.py
@@ -17,10 +17,8 @@ def test_lock_safety(self):
17 17
         # Try running the handler, it will fail in load_middleware
18 18
         handler = WSGIHandler()
19 19
         self.assertEqual(handler.initLock.locked(), False)
20  
-        try:
  20
+        with self.assertRaises(Exception):
21 21
             handler(None, None)
22  
-        except:
23  
-            pass
24 22
         self.assertEqual(handler.initLock.locked(), False)
25 23
         # Reset settings
26 24
         settings.MIDDLEWARE_CLASSES = old_middleware_classes
5  tests/regressiontests/queries/tests.py
@@ -1677,10 +1677,7 @@ def test_evaluated_queryset_as_argument(self):
1677 1677
         list(n_list)
1678 1678
         # Use the note queryset in a query, and evalute
1679 1679
         # that query in a way that involves cloning.
1680  
-        try:
1681  
-            self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
1682  
-        except:
1683  
-            self.fail('Query should be clonable')
  1680
+        self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
1684 1681
 
1685 1682
 
1686 1683
 class EmptyQuerySetTests(TestCase):
22  tests/regressiontests/transactions_regress/tests.py
... ...
@@ -1,7 +1,6 @@
1 1
 from __future__ import absolute_import
2 2
 
3  
-from django.core.exceptions import ImproperlyConfigured
4  
-from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS
  3
+from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS, DatabaseError
5 4
 from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError
6 5
 from django.test import TransactionTestCase, skipUnlessDBFeature
7 6
 from django.test.utils import override_settings
@@ -151,21 +150,14 @@ def create_system_user():
151 150
         # Create a user
152 151
         create_system_user()
153 152
 
154  
-        try:
155  
-            # The second call to create_system_user should fail for violating a unique constraint
156  
-            # (it's trying to re-create the same user)
  153
+        with self.assertRaises(DatabaseError):
  154
+            # The second call to create_system_user should fail for violating
  155
+            # a unique constraint (it's trying to re-create the same user)
157 156
             create_system_user()
158  
-        except:
159  
-            pass
160  
-        else:
161  
-            raise ImproperlyConfigured('Unique constraint not enforced on django.contrib.auth.models.User')
162 157
 
163  
-        try:
164  
-            # Try to read the database. If the last transaction was indeed closed,
165  
-            # this should cause no problems
166  
-            _ = User.objects.all()[0]
167  
-        except:
168  
-            self.fail("A transaction consisting of a failed operation was not closed.")
  158
+        # Try to read the database. If the last transaction was indeed closed,
  159
+        # this should cause no problems
  160
+        User.objects.all()[0]
169 161
 
170 162
     @override_settings(DEBUG=True)
171 163
     def test_failing_query_transaction_closed_debug(self):

0 notes on commit 335a9f9

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