Skip to content

Commit

Permalink
Removed many uses of bare "except:", which were either going to a) si…
Browse files Browse the repository at this point in the history
…lence real issues, or b) were impossible to hit.
  • Loading branch information
Alex Gaynor committed Sep 7, 2012
1 parent 257c401 commit 335a9f9
Show file tree
Hide file tree
Showing 10 changed files with 31 additions and 48 deletions.
10 changes: 5 additions & 5 deletions django/contrib/localflavor/hr/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""
from __future__ import absolute_import, unicode_literals

import datetime
import re

from django.contrib.localflavor.hr.hr_choices import (
Expand Down Expand Up @@ -91,17 +92,16 @@ def clean(self, value):
dd = int(matches.group('dd'))
mm = int(matches.group('mm'))
yyy = int(matches.group('yyy'))
import datetime
try:
datetime.date(yyy,mm,dd)
except:
datetime.date(yyy, mm, dd)
except ValueError:
raise ValidationError(self.error_messages['date'])

# Validate checksum.
k = matches.group('k')
checksum = 0
for i,j in zip(range(7,1,-1),range(6)):
checksum+=i*(int(value[j])+int(value[13-i]))
for i, j in zip(range(7, 1, -1), range(6)):
checksum += i * (int(value[j]) + int(value[13 - i]))
m = 11 - checksum % 11
if m == 10:
raise ValidationError(self.error_messages['invalid'])
Expand Down
22 changes: 11 additions & 11 deletions django/contrib/localflavor/ro/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"""
from __future__ import absolute_import, unicode_literals

import datetime

from django.contrib.localflavor.ro.ro_counties import COUNTIES_CHOICES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError, Field, RegexField, Select
Expand Down Expand Up @@ -69,10 +71,9 @@ def clean(self, value):
if value in EMPTY_VALUES:
return ''
# check birthdate digits
import datetime
try:
datetime.date(int(value[1:3]),int(value[3:5]),int(value[5:7]))
except:
datetime.date(int(value[1:3]), int(value[3:5]), int(value[5:7]))
except ValueError:
raise ValidationError(self.error_messages['invalid'])
# checksum
key = '279146358279'
Expand Down Expand Up @@ -118,7 +119,7 @@ def clean(self, value):
# search for county name
normalized_CC = []
for entry in COUNTIES_CHOICES:
normalized_CC.append((entry[0],entry[1].upper()))
normalized_CC.append((entry[0], entry[1].upper()))
for entry in normalized_CC:
if entry[1] == value:
return entry[0]
Expand Down Expand Up @@ -153,8 +154,8 @@ def clean(self, value):
value = super(ROIBANField, self).clean(value)
if value in EMPTY_VALUES:
return ''
value = value.replace('-','')
value = value.replace(' ','')
value = value.replace('-', '')
value = value.replace(' ', '')
value = value.upper()
if value[0:2] != 'RO':
raise ValidationError(self.error_messages['invalid'])
Expand Down Expand Up @@ -185,10 +186,10 @@ def clean(self, value):
value = super(ROPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return ''
value = value.replace('-','')
value = value.replace('(','')
value = value.replace(')','')
value = value.replace(' ','')
value = value.replace('-', '')
value = value.replace('(', '')
value = value.replace(')', '')
value = value.replace(' ', '')
if len(value) != 10:
raise ValidationError(self.error_messages['invalid'])
return value
Expand All @@ -202,4 +203,3 @@ class ROPostalCodeField(RegexField):
def __init__(self, max_length=6, min_length=6, *args, **kwargs):
super(ROPostalCodeField, self).__init__(r'^[0-9][0-8][0-9]{4}$',
max_length, min_length, *args, **kwargs)

2 changes: 1 addition & 1 deletion django/core/cache/backends/memcached.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def __init__(self, server, params):
)
try:
import memcache
except:
except ImportError:
raise InvalidCacheBackendError(
"Memcached cache backend requires either the 'memcache' or 'cmemcache' library"
)
Expand Down
2 changes: 1 addition & 1 deletion django/core/mail/backends/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def send_messages(self, email_messages):
stream_created = self.open()
for message in email_messages:
self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-'*79)
self.stream.write('-' * 79)
self.stream.write('\n')
self.stream.flush() # flush after each message
if stream_created:
Expand Down
5 changes: 1 addition & 4 deletions django/db/backends/sqlite3/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,4 @@ def _sqlite_format_dtdelta(dt, conn, days, secs, usecs):
return str(dt)

def _sqlite_regexp(re_pattern, re_string):
try:
return bool(re.search(re_pattern, re_string))
except:
return False
return bool(re.search(re_pattern, re_string))
5 changes: 2 additions & 3 deletions django/http/multipartparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,10 @@ def __init__(self, META, input_data, upload_handlers, encoding=None):
if not boundary or not cgi.valid_boundary(boundary):
raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)


# Content-Length should contain the length of the body we are about
# to receive.
try:
content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH',0)))
content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH', 0)))
except (ValueError, TypeError):
content_length = 0

Expand Down Expand Up @@ -178,7 +177,7 @@ def parse(self):

content_type = meta_data.get('content-type', ('',))[0].strip()
try:
charset = meta_data.get('content-type', (0,{}))[1].get('charset', None)
charset = meta_data.get('content-type', (0, {}))[1].get('charset', None)
except:
charset = None

Expand Down
2 changes: 1 addition & 1 deletion tests/regressiontests/file_uploads/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def test_unicode_file_name(self):

try:
os.unlink(file1.name)
except:
except OSError:
pass

self.assertEqual(response.status_code, 200)
Expand Down
4 changes: 1 addition & 3 deletions tests/regressiontests/handlers/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ def test_lock_safety(self):
# Try running the handler, it will fail in load_middleware
handler = WSGIHandler()
self.assertEqual(handler.initLock.locked(), False)
try:
with self.assertRaises(Exception):
handler(None, None)
except:
pass
self.assertEqual(handler.initLock.locked(), False)
# Reset settings
settings.MIDDLEWARE_CLASSES = old_middleware_classes
Expand Down
5 changes: 1 addition & 4 deletions tests/regressiontests/queries/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1677,10 +1677,7 @@ def test_evaluated_queryset_as_argument(self):
list(n_list)
# Use the note queryset in a query, and evalute
# that query in a way that involves cloning.
try:
self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
except:
self.fail('Query should be clonable')
self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')


class EmptyQuerySetTests(TestCase):
Expand Down
22 changes: 7 additions & 15 deletions tests/regressiontests/transactions_regress/tests.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import absolute_import

from django.core.exceptions import ImproperlyConfigured
from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS
from django.db import connection, connections, transaction, DEFAULT_DB_ALIAS, DatabaseError
from django.db.transaction import commit_on_success, commit_manually, TransactionManagementError
from django.test import TransactionTestCase, skipUnlessDBFeature
from django.test.utils import override_settings
Expand Down Expand Up @@ -151,21 +150,14 @@ def create_system_user():
# Create a user
create_system_user()

try:
# The second call to create_system_user should fail for violating a unique constraint
# (it's trying to re-create the same user)
with self.assertRaises(DatabaseError):
# The second call to create_system_user should fail for violating
# a unique constraint (it's trying to re-create the same user)
create_system_user()
except:
pass
else:
raise ImproperlyConfigured('Unique constraint not enforced on django.contrib.auth.models.User')

try:
# Try to read the database. If the last transaction was indeed closed,
# this should cause no problems
_ = User.objects.all()[0]
except:
self.fail("A transaction consisting of a failed operation was not closed.")
# Try to read the database. If the last transaction was indeed closed,
# this should cause no problems
User.objects.all()[0]

@override_settings(DEBUG=True)
def test_failing_query_transaction_closed_debug(self):
Expand Down

0 comments on commit 335a9f9

Please sign in to comment.